Results 1 to 3 of 3
- 09-05-2010, 08:15 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 13
- Rep Power
- 0
After catching the exception thrown
Part of my school assignment is asking us to throw an exception if the answer is zero or less than zero. After catching the exception, I would like to re-ask the same question. I tried adding the same question after the catch statement but if I enter zero, it does not re-ask the same question.
My code is below.
try {
System.out.print("Enter tutored time in minutes: ");
matrix[i][0] = input.nextDouble();
if (matrix[i][0] <= 0);
throw new ArithmeticException("Minutes must be greater than zero");
}
catch (ArithmeticException ex) {
System.out.println("Minutes must be greater than 0");
}
/* if I add the following statements here to re-ask the same question:
**System.out.print("Enter tutored time in minutes: ");
**matrix[i][0] = input.nextDouble();
**it will not re-ask the same question if the answer is zero again */
- 09-05-2010, 09:21 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,421
- Blog Entries
- 7
- Rep Power
- 26
Your code begs for a while loop; a while loop with a try-catch block in its body. If the loop ends a positive number was given by the user. If I were you I'd stick all that code in a separate method that only returns correct (positive) answers given by the user; it handles those try-catch blocks itself. A skeleton of the code could be:
Java Code:int getAnswer() { int ans= -1; while (ans < 0) { // as long as no correct answer given ... try { ans= ...; // get answer from the user; if (ans < 0) throw ArithmeticException("incorrect anser:"+ans); return ans; // pass back a correct answer } catch (ArithmeticException ae) { System.out.println(ae.getMessage()); } } return -1; // never reached }
Jos
- 09-05-2010, 02:29 PM #3
Member
- Join Date
- Aug 2010
- Posts
- 13
- Rep Power
- 0
Similar Threads
-
Execution stuck at ObjectInputStream .readObject() with NO Exception thrown.JAVA BUG?
By r00tb33r in forum NetworkingReplies: 2Last Post: 06-01-2010, 02:58 AM -
Catching exception from another library (class)
By ezilka in forum New To JavaReplies: 15Last Post: 05-26-2010, 06:59 AM -
How many no. of exceptions can be thrown????
By Stephen Douglas in forum New To JavaReplies: 8Last Post: 04-30-2010, 05:12 PM -
unreported exception IOException -- Yet I AM catching it?
By Agathorn in forum New To JavaReplies: 2Last Post: 09-18-2009, 11:22 PM -
Which exception is thrown.....
By money123 in forum New To JavaReplies: 1Last Post: 07-30-2007, 03:41 PM
Bookmarks