nill nill - 4 years ago 81
Java Question

Exception Handling with External Loop

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;
}
}
}

Answer Source

Try this:

    Scanner inRead = null;
    float sum = 0;
    int count = 0;
    while(true){
        try{
            inRead = new Scanner(System.in);
            sum+= inRead.nextFloat();
            if(count == 1) {
                count = 0;
            }
        }
        catch (InputMismatchException e){
            if (count == 1){
                System.out.println(sum);
                break;
            }
            else{
                inRead = null;
                count+=1;
            }
        }
    }

The counter increments 2 in your code because when you encounter an InputMismatchException in a nextFloat() method. the second nextFloat() you will encounter will not work because you need to create a new Scanner for that because it causes an error earlier in your loop, and I add if(count == 1) when you need to reset it to 0 so it can satisfy your problem to stop and add all when two consecutive non-float will be inputted.

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