Underscore in integer input causes error in java

Viewed 63

As is specified in the Java Standard Editions docs, any number of underscore characters (_) can appear anywhere between digits in a numerical literal, like so:- int number = 100_000;.

Out of curiosity, I tried inputting an underscore separated value (100_000) to an input that is expecting an integer. The code:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int basicAmount = sc.nextInt();
    }
}

This resulted in a generic error message.

So my questions are:

  1. Why does this happen? Why am I not allowed to input numeric values containing underscores?
  2. Is there a way to allow users to input numeric values with underscores?
1 Answers

The docs you quoted is about Java Source Code. It is saying that things like this are possible:

int i = 123_456_789; // same as int i = 123456789;

The text that Scanner reads is not Java source code.

The relevant documentation you should read in this case is Scanner.nextInt, which will bring you to its acceptable format specified here. It is clear that Scanner.nextInt does not accept numbers with underscores.

One simple way to read numbers with underscores in them is to just read a token, and remove all the underscores in it:

int input = Integer.parseInt(sc.next().replaceAll("_", ""));
Related