I want to have an ArrayList
that records user entries and ends when it receives a non-integer value but I am getting an infinite loop and I don't know why.
public class Tryout1
{
public static void main(String[] args)
{
ArrayList entries = new ArrayList();
Scanner obj1 = new Scanner(System.in);
System.out.println("enter numbers");
int i = obj1.nextInt();
boolean accumulating = obj1.hasNextInt(); //check int
while(accumulating) {
entries.add(i);
}
System.out.println(entries);
}
}
CodePudding user response:
you should move your check inside the loop, so it will check every time before the next loop is executed. In your code, the check is only performed once.
public class tryout1 {
public static void main(String[] args) {
ArrayList entries = new ArrayList();
Scanner obj1 = new Scanner(System.in);
System.out.println("enter numbers");
do {
// get the next int
int i = obj1.nextInt();
entries.add(i);
} while (obj1.hasNextInt()); // <- check here for nextInt
System.out.println(entries);
}
}