Reputation: 45
Ive written a small Java code to calculate the product of two integers input by the user using Scanner. The user is forced to input integer values. The code is shown below.
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
int x=0,y=0;
Scanner sc=new Scanner(System.in);
//Asks for the first number until the user inputs an integer
System.out.println("First number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. First number:");
sc.nextLine();
}
x=sc.nextInt();
//Asks for the second number until the user inputs an integer
System.out.println("Second number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. Second number:");
sc.nextLine();
}
y=sc.nextInt();
//Show result
System.out.println(x+"*"+y+"="+x*y);
}
}
The loop for the first number works fine. But, the second doesn't: if the user inputs something that is not an integer value, the message "Not valid. Second number:" is shown twice!
First number:
g
Not valid. First number:
2
Second number:
f
Not valid. Second number:
Not valid. Second number:
4
2*4=8
What is the reason for this behaviour? I guess I'm doing something wrong.
I've tried to use two different Scanners (one for each number) and the problem dissapears, but I don't think that creating lots of instances is the correct path.
Can anybody help?
Thanks.
Upvotes: 1
Views: 342
Reputation: 44834
Because even after accepting the first int value there is still the newline character to consume,
so change to
x=sc.nextInt();
sc.nextLine();
Upvotes: 2