Reading integers and strings from one console line
The problem is this:
I have two programs that take input from the console, but in different ways: 1)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
2)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
// input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
In the first case, 1 take input in 2 different lines like
1 2
so it gives the correct answer, but in the second case, I removed the operator input.nextLine()
to type the inputs on one line, like:
1 2
it gives me numerical formatted exception, why ?? and also suggest me how can I read integers and strings from one console line.
source to share
The problem is what str
matters " 2"
, and leading space is not legal syntax for parseInt()
. You need to either skip the space between the two numbers in the input, or trim the space in str
before parsing like int
. To skip a space, do the following:
input.skip("\\s*");
String str = input.nextLine();
To strip the space str
before parsing, do the following:
int temp2 = Integer.parseInt(str.trim());
You can also get fancy and read two parts of a line in one go:
if (input.findInLine("(\\d+)\\s+(\\d+)") == null) {
// expected pattern was not found
System.out.println("Incorrect input!");
} else {
// expected pattern was found - retrieve and parse the pieces
MatchResult result = input.match();
int temp1 = Integer.parseInt(result.group(1));
int temp2 = Integer.parseInt(result.group(2));
int total = temp1+temp2;
System.out.println(total);
}
source to share