I am doing an exercise in which the user has to input a signed four digit decimal number such as +3364, -1293, +0007, etc using Java programming language.
As far as I know, Java does not support a primitive type decimal.
My questions are:
- How can I enter numbers like above?
- How can I provide a +, – sign for the above numbers?
UPDATE
The code below shows a snippet in which it asks the user to enter a valid number (no characters) – the unary + is not working using the code below!! is there a way to fix it.
public int readInt() {
boolean continueLoop = true;
int number = 0;
do {
try {
number = input.nextInt();
continueLoop = false;
} // end try
catch (InputMismatchException inputMismatchException) {
input.nextLine();
/** discard input so user can try again */
System.out.printf("Invalid Entry ?: ");
} // end of catch
} while (continueLoop); // end of do...while loop
return number;
} // end of method readInt()
Java has 8 primitive (non-Object/non-Reference) types:
booleancharbyteshortintlongfloatdoubleIf, by “decimal” you mean “base 10 signed integer”, then yes, Java supports that via
byte,short,intandlong. Which one you use will depend on the input ranges, butintis the most common, from what I’ve seen.If, by “decimal” you mean “base 10 signed floating-point number with absolute precision” similar to C#’s
Decimaltype, then no, Java does not have that.If
Scanner.nextIntis throwing an error for you, like it is me, then the following should work:Alternatively, you can do it like this:
Basically just remove the ‘+’ sign if there’s one and then parse it. If you’re going to be doing programming, learning regular expressions is very useful, which is why I gave you that, instead. But if this is homework and you’re worried that the teacher will get suspicious if you use something that is beyond the scope of the course, then by all means do not use the regular expression approach.