
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

File ScanInts.java is a program that contains a do while loop that does the following:
After the user enters an empty string as input, the loop stops and the program displays the sum of the integers.
Save ScanInts.java to C:|temp and compile and run it. If you give it the input
it should print
The sum of the integers is 100.
Try some other inputs as well.
Now try a line that contains both integers and a non-numeric value such as
xyz
You should get a NumberFormatException when the program tries to call Integer.parseInt on " xyz ". One way around this is to put the do while loop inside a try , and catch the NumberFormatException but not do anything with it. This way if it is not an integer it does not cause an error; it goes to the exception handler, which does nothing. Do this as follows:
Modify the program to add a try statement that encompasses the entire do while loop. The try and โ { โ should go before the do and the โ } โ after the while. Catch a NumberFormatException , and have an empty body for the catch.
Compile and run the program, and enter some integers and then a non-numeric value. You should find that it stops at the first non-integer. However the problem is that since the entire loop is inside the try , when an exception is thrown the loop is terminated. To fix this, move the try and catch inside the do while loop. Now when an exception is thrown, the next statement is the next iteration of the loop, so the next input is processed.