| | |
Problem using exceptions and looping
Thread Solved |
I'm having a little trouble with one of my exceptions. The following code is just a simple division of two integers. I have built two exception to handle an InputMismatch and divide by zero. What I want to happen is when there is an exception, I want the program to return to let the user enter more data. If there is no exception, I want the program to end. The problem occurs when I enter words instead of numbers to make the exception InputMismatch work. When this happens the program goes into an infinity loop and I have to kill the program. Can somebody please look at my code and let me know what I'm doing wrong?
Also, do I need a throw for the InputMismatch?
Also, do I need a throw for the InputMismatch?
Java Syntax (Toggle Plain Text)
import java.util.Scanner; import java.util.InputMismatchException; public class P4Exceptions { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n1, n2; double r = 0; boolean continueLoop = true; // determines if more input is needed while ( continueLoop ) { try { System.out.println("Enter two numbers. I will compute the ratio:"); n1 = scan.nextInt(); n2 = scan.nextInt(); r = (double) n1 / n2; if (n2 == 0) throw new ArithmeticException(); System.out.println("The ratio r = " + r ); continueLoop = false; } catch ( ArithmeticException arithmeticException ) { System.out.println("There was an exception: Divide by zero. Try again\n"); } catch ( InputMismatchException inputMismatchException ) { System.out.println("You must enter an integer. Try again.\n"); } } } }
I think it has something to do with the way the stream works--
if you call the method nextInt it will return the value on the line and attempt to the next line of code.
I'm almost certain that because the type returned was not the type that should be returned, the method nextInt threw an exception and most likely returned 0 (since the method is an int and must therefore return a valid argument). Upon doing so, the stream might not have been flushed, leaving the value on the line and for it to be re-evaluated again since the line jump was unsuccessful.
Here is the edit--
if you call the method nextInt it will return the value on the line and attempt to the next line of code.
I'm almost certain that because the type returned was not the type that should be returned, the method nextInt threw an exception and most likely returned 0 (since the method is an int and must therefore return a valid argument). Upon doing so, the stream might not have been flushed, leaving the value on the line and for it to be re-evaluated again since the line jump was unsuccessful.
Here is the edit--
Java Syntax (Toggle Plain Text)
import java.util.Scanner; import java.util.InputMismatchException; public class P4Exceptions { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n1, n2; double r = 0; boolean continueLoop = true; // determines if more input is needed while ( continueLoop ) { try { System.out.println("Enter two numbers. I will compute the ratio:"); n1 = Integer.parseInt(scan.nextLine()); n2 = Integer.parseInt(scan.nextLine()); r = (double) n1 / n2; if (n2 == 0) throw new ArithmeticException(); System.out.println("The ratio r = " + r ); continueLoop = false; } catch ( ArithmeticException arithmeticException ) { System.out.println("There was an exception: Divide by zero. Try again\n"); n1 = 0; n2 = 0; } catch ( NumberFormatException inputMismatchException ) { System.out.println("You must enter an integer. Try again.\n"); n1 = 0; n2 = 0; } catch(Exception e) { System.out.println(e); n1 = 0; n2 = 0; } } } }
Last edited by Alex Edwards; Jun 5th, 2008 at 10:08 pm.
•
•
Join Date: Aug 2006
Posts: 137
Reputation:
Solved Threads: 11
I think I might have made the same mistake. The way Scanner works, is by matching patterns in some stream. When you use nextInt() it will attempt to find an integer value in the input stream. If it is successful, it will move forward in the stream. If it is not successful then it will not move forward. Thus when you input words, you remain on the same input until you call the appropriate Scanner method to match it and proceed.
So add
So you'd have:
This will allow the scanner object to skip the error and move forward in the input stream. By the way, perhaps if would be best to check if n2 is zero before actually doing the division
it works regardless, but it's still an unneeded calculation if there is an error.
So add
scan.nextLine(); after the line with your message:System.out.println("You must enter an integer. Try again.\n");So you'd have:
java Syntax (Toggle Plain Text)
catch (InputMismatchException inputMismatchException) { System.out.println("You must enter an integer. Try again.\n"); scan.nextLine(); }
This will allow the scanner object to skip the error and move forward in the input stream. By the way, perhaps if would be best to check if n2 is zero before actually doing the division
Last edited by PoovenM; Jun 6th, 2008 at 8:44 am.
![]() |
Similar Threads
- Strange shutdown problem, self-reboot (Windows NT / 2000 / XP)
- what's with gcc? (C++)
Other Threads in the Java Forum
- Previous Thread: Null Pointer
- Next Thread: please help me solve this! How to search in java using MYSQL database?
| Thread Tools | Search this Thread |
-xlint add android api applet application applications array arrays automation bank bi binary blackberry bluetooth chat class client code compile compiler component database development digit eclipse equation error event fractal freeze functiontesting game gameprogramming givemetehcodez graphics gui health html hyper ide idea image infinite input int integer j2me java javame javaprojects jetbrains jni jpanel jtable julia learningresources linux list login loop main map method methods mobile myregfun netbeans newbie nonstatic notdisplaying pearl problem program programming project qt recursion scanner screen scrollbar server set sms sort sorting spamblocker sql sqlserver string superclass swing system text-file thread threads tree variablebinding windows xor





