CanKer DiAlike CanKer DiAlike - 2 years ago 83
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

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

Scanner in = new Scanner(;
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: ");;
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
but when im using
gives me that problem or when I use only

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: ");;
chain[x] = in.nextInt();
if(chain[x] == 0) {
System.out.println("This app doesn't accept 0");

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download