CanKer DiAlike CanKer DiAlike - 6 months ago 15
Java Question

Java: nextInt() validation doesn't work property

I'm not Java expert and I have a problem. I'm getting data from the keyboard using Scanner, but I have to do 2 validations before registering the data to my array. One is, the data doesn't have to be a string and I'm using

!in.hastNextInt()
to validate wherein the Scanner instance, and the other one is that the data doesn't have to be
0
. and the code I'm using is the next one:

Scanner in = new Scanner(System.in);
int chain [] = new int [10];

System.out.println("Welcome, please enter the values for the array: ");
for(int x = 0;x < chain.length; x++) {
System.out.print((x+1) +": ");
while(!in.hasNextInt() || in.nextInt()==0) {
System.out.print("This app doesn't accept letters, symbols or zeros: ");
in.next();
}
chain[x] = in.nextInt();
}


and unfortunately, when I run the program it asks me twice per each statement, for example, asks me twice per position 0 of the array and twice per position 1 of the array.

Does anyone have an idea of what's happening?
It works perfectly with
!in.hasNextInt()
but when im using
in.nextInt()==0
gives me that problem or when I use only
in.nextInt()==0
alone

what is my error and what do you recommend me to change in my code to make it work well.
I appreciate any help

Thank you in advance

as @Andreas told in his answer I had to change my code and the new good one is:

for(int x = 0;x < chain; x++) {
System.out.print((x+1) +": ");
while(!in.hasNextInt()) {
System.out.print("This app doesn't accept letters or symbols: ");
in.next();
}
chain[x] = in.nextInt();
if(chain[x] == 0) {
System.out.println("This app doesn't accept 0");
--x;
}
}

Answer

nextInt() consumes the token, so when you do in.nextInt()==0, you read a token and loop if the value is zero.

If the token is not zero, the loop ends and you execute chain[x] = in.nextInt(), which reads the next token. Not the same token again.

You should capture the value in a variable, then check for zero, and use it if appropriate.

Comments