I'm trying to handle a user input and allow for only floats to be entered. The number of floats that can be entered is unlimited, but if two consecutive non-floats are entered the program will end. When the program ends it will print the sum of all the numbers.
The problem is that whenever I run this it immediately runs through the while loop and increases the count to 2 and breaks the loop. You're only able to enter one non-float before it cancels out.
while(true){
try{
sum+= inRead.nextFloat();
}
catch (InputMismatchException e){
if (count == 2){
System.out.println(sum);
break;
}
else{
count+=1;
}
}
}
EDIT: As a few of you had pointed out that count should be initialized before the while loop
Scanner inRead = new Scanner(System.in);
float sum = 0;
int count = 0;
while(true){
try{
sum+= inRead.nextFloat();
}
catch (InputMismatchException e){
if (count == 2){
System.out.println(sum);
break;
}
else{
count+=1;
}
}
}