Reputation: 27
i have a method that continues to loop until the user inputs a number within a set range. Basically it reads the size on an arraylist, and validates that the users input is greater than -1, and and less than the arraylist size. Howver, i cant seem to get the boolean logic right and it still accepts bad numbers or only one side of the range works. Here is the code
public void Verify()
{
do {
System.out.printf("Enter the number\n");
while (!input.hasNextInt())
{
System.out.printf("Enter the number\n");
input.next();
}
choice = input.nextInt();
} while (choice < 0 && choice > mov.getArrayListSize());//<--- this part
}
Upvotes: 1
Views: 244
Reputation: 28292
So here's the problem
while (choice < 0 && choice > mov.getArrayListSize());
What this says is: keep looping until the value of choice is both less than zero and simultaneously greater than the size of the array. Let's look at some number lines:
xxxxxxxxxx
----------+---------+------------> ... this shows a solution for choice < 0
0 len
xxxxxxxxxxxx
----------+---------+------------> ... this shows a solution for choice > len
0 len
----------+---------+------------> ... this shows a solution for the logical AND
0 len
There is no solution for choice that can possibly be both less than zero and more than the array length. What you almost certainly mean to use is logical OR, not AND:
while (choice < 0 || choice > mov.getArrayListSize());
The solution on the number line for this is
xxxxxxxxxx xxxxxxxxxxxx
----------+---------+------------> ... this shows a solution for choice > len
0 len
The loop would continue until the value fell inside the 0-len range, which seems like what you need here.
Upvotes: 1