Reputation: 1
This is a calculator program. When I write it like that:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int x1 = input.nextInt();
int x2 = input.nextInt();
String x3 = input.nextLine();
if ("+".equals(x3)){
int r= x1 + x2;
System.out.println(r);
} else if ("-".equals(x3)) {
int r= x1 - x2;
System.out.println(r);
} else if ("*".equals(x3)) {
int r= x1 * x2;
System.out.println(r);
} else if ("/".equals(x3)) {
int r= x1 / x2;
System.out.println(r);
} else if ("%".equals(x3)) {
int r= x1 % x2;
System.out.println(r);
} else {
System.out.println("invalid input");
}
}
The program doesn't wait to take the third input. When I tried to to make another scanner object for the third input alone, the code worked well. Also when I tried to switch the order by which I take the inputs so that I take the string input first, the code worked well. can anyone tell me what's going on?
Upvotes: 0
Views: 800
Reputation: 714
I solved it by adding a function that parses a String
to an int
. You need to use input.nextLine()
, pass it to the function along with your Scanner
, and then use that value. If the String is not a number, it will ask for another input.
private static int parseInt(String s, Scanner input) {
try {
return Integer.parseInt(s);
} catch(NumberFormatException e) {
return parseInt(input.nextLine(), input);
}
}
You can use it like this:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int x1 = parseInt(input.nextLine(), input);
int x2 = parseInt(input.nextLine(), input);
String x3 = input.nextLine();
if ("+".equals(x3)){
int r= x1 + x2;
System.out.println(r);
} else if ("-".equals(x3)) {
int r= x1 - x2;
System.out.println(r);
} else if ("*".equals(x3)) {
int r= x1 * x2;
System.out.println(r);
} else if ("/".equals(x3)) {
int r= x1 / x2;
System.out.println(r);
} else if ("%".equals(x3)) {
int r= x1 % x2;
System.out.println(r);
} else {
System.out.println("invalid input");
}
}
Upvotes: 1
Reputation: 4191
The problem is input.nextInt()
is reading only the digits and input.nextLine()
reads empty string afterwards. Because of that, x3
is considered to be an empty string and it gives an error at the end.
@Lóránt Viktor Gerber suggestion works well.
Also, I would suggest you make sure that you read the right inputs (you can print out.) and don't trust to the user who will input. Your program will give an exception
if users give wrong inputs such as string
or double
instead of integer
.
Upvotes: 0