Computer Science Canada Newbish question - Exception loop? |
Author: | Dibbie [ Tue May 01, 2012 4:57 pm ] |
Post subject: | Newbish question - Exception loop? |
First off, hello, im new to this forums, so hello to everyone! =D Secondly, i know this is not the right area to post this, since this is a Java related issue, but it wont let me post in Java section, sais i dont have the rights to. Anyway, on to my question: So, I made a program thats a simple calculator, and this is my first year programming (iv been useing Java and programming for a good 2 months now, im not in school for it) Anyway, so the problem is that I donno how to loop it, so it works properly, heres whats suposto happen: Enter your first number to add: g That's not a number. Enter your first number to add: Heres what happens: Enter your first number to add: g That's not a number. + Enter your second number: Here is my code, can someone please tell me what im doing wrong here: if (op == 'A' || op == 'a') { while (exception==null) { write ("Enter your first number to add: "); try { num1 = readInt (); } catch(Exception e) { System.out.println("That's not a number."); exception=e.toString(); } } writeLine ("+"); write ("Enter your second number: "); num2 = readInt (); sum = num1 + num2; writeLine (num1 + " + " + num2 + " = " + sum); writeLine (""); writeLine ("Back to menu? (Y|N)"); writeLine (""); op = readChar (); } (Also, just so you understand the program, its a simple calculator that adds, subtracts, multiplys, or devides) Dibbie Simple Calculator selected! A (Add) S (Subtract) M (Multiply) D (Divide) ^ Above you pick wich option you want, in the error shown above, i picked A, add |
Author: | DemonWasp [ Tue May 01, 2012 5:13 pm ] | ||
Post subject: | RE:Newbish question - Exception loop? | ||
What's happening is that when you enter a non-number, the readInt() call fails and throws an exception (hopefully a NumberFormatException). Then, the 'exception' variable gets set to a string representing that exception, then exception is not null, so the loop does not continue. The more straightforward way to write this kind of thing is:
|