JaynineReturns JaynineReturns - 29 days ago 6
Java Question

Reading user input: No value entered v one value entered

I'm having an issue with one of my methods:

public static int readIntoArray(Scanner input, int[] nums) {
int i = 0;
int count = 0; //Will hold the number of values in array

if (input.hasNextInt() == false) {
count = 0;
}

else{
int num = input.nextInt();

do {
nums[i] = num;
i++;
count++;
num = input.nextInt();
if (input.hasNextInt() == false) {
nums[i] = num;
count++;
}
else {

}
} while(input.hasNextInt() && i < 100);
}

return count;
}


This is one method in my program. My problem before was that I would get an error if the user hit enter without entering any values. I fixed that by creating the if-else statement in my code above.

But since that is the beginning part of the method I get an error when the user enters only one value. I'm not sure how to fix this because if I move the first if statement then I'll get an error when the user enters no values. I'm confused as to how to get this to play nice with the two different scenarios.

Basically the method, as it is above, won't work when the user enters one value.

Answer

Try this instead; it's much more simple:

public static int readIntoArray(Scanner input, int[] nums) {

    int count = 0; // Will hold the number of values in array

    while(input.hasNextInt() && count < 100) {
        nums[count] = input.NextInt();
        count++;
    }

    return count;
}

Assume you only have one value in the input. Your code breaks because right after you increment count, you set num to the next int (which doesn't exist):

num = input.nextInt(); // there isn't a next int!

Also, I think the logic is off in the if loop in the do while. Pretend you have one input 3, and we've resolved the single-input error. Right before the second if statement:

  • i is 1.
  • count is 1.
  • nums[0] is 3.

    Next, if (input.hasNextInt() == false) will evaluate to true because 3 was our only input. Then:

  • i is still 1.

  • count is now 2.
  • nums[1] is 3.

I'm almost certain this isn't what you want to happen.