Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive type decimal in Java - User Entry

Tags:

java

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:

  1. How can I enter numbers like above?
  2. 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()
like image 769
Sinan Avatar asked Dec 22 '25 11:12

Sinan


2 Answers

Java has 8 primitive (non-Object/non-Reference) types:

  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double

If, by "decimal" you mean "base 10 signed integer", then yes, Java supports that via byte, short, int and long. Which one you use will depend on the input ranges, but int is 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 Decimal type, then no, Java does not have that.

If Scanner.nextInt is throwing an error for you, like it is me, then the following should work:

/* Create a scanner for the system in. */
Scanner scan = new Scanner(System.in);
/*
 * Create a regex that looks for numbers formatted like:
 * 
 * A an optional '+' sign followed by 1 or more digits; OR A '-'
 * followed by 1 or mored digits.
 * 
 * If you want to make the '+' sign mandatory, remove the question mark.
 */
Pattern p = Pattern.compile("(\\+?(\\d+))|(\\-\\d+)");

/* Get the next token from the input. */
String input = scan.next();
/* Match the input against the regular expression. */
Matcher matcher = p.matcher(input);
/* Does it match the regular expression? */
if (matcher.matches()) {
    /* Declare an integer. */
int i = -1;
/*
 * A regular expression group is defined as follows:
 * 
 * 0 : references the entire regular expression. n, n != 0 :
 * references the specified group, identified by the nth left
 * parenthesis to its matching right parenthesis. In this case there
 * are 3 left parenthesis, so there are 3 more groups besides the 0
 * group:
 * 
 * 1: "(\\+?(\\d+))"; 2: "(\\d+)"; 3: "(\\-\\d+)"
 * 
 * What this next code does is check to see if the positive integer
 * matching capturing group didn't match. If it didn't, then we know
 * that the input matched number 3, which refers to the negative
 * sign, so we parse that group, accordingly.
 */
if (matcher.group(2) == null) {
    i = Integer.parseInt(matcher.group(3));
} else {
    /*
     * Otherwise, the positive group matched, and so we parse the
     * second group, which refers to the postive integer, less its
     * '+' sign.
     */
        i = Integer.parseInt(matcher.group(2));
    }
    System.out.println(i);
} else {
    /* Error handling code here. */
}

Alternatively, you can do it like this:

    Scanner scan = new Scanner(System.in);
    String input = scan.next();
    if (input.charAt(0) == '+') {
        input = input.substring(1);
    }
    int i = Integer.parseInt(input);
    System.out.println(i);

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.

like image 180
Jesus is Lord Avatar answered Dec 24 '25 00:12

Jesus is Lord


Use Scanner:

Scanner scan = new Scanner(System.in);
System.out.print("Enter 3 integer numbers: ");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
System.out.print("You have entered: " + a + " | " + b + " | " + c);

OUTPUT:

Enter 3 integer numbers: +3364 -1293 +0007
You have entered: 3364 | -1293 | 7


A side note: Be careful when you are using leading 0's with integer numbers like 0007, because it's interpreted in Java as octal number not decimal number. So, 010 is actually 8 in decimal base system, not 10.

System.out.print(010);

OUTPUT:

8

UPDATE:

Note that Scanner requires the signs + and - to be sticked to the number like +5432 and -5432, not as + 5432 nor - 5432.

like image 44
Eng.Fouad Avatar answered Dec 24 '25 01:12

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!