Results 1 to 18 of 18
- 10-12-2010, 01:03 AM #1
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
try-catch InputMismatchException in a while loop
I've been trying to make this program check whether if the user enters an integer or non integer when they enter a number to be checked whether it's prime or not. But whenever I enter a string, it keeps repeating the error message "Not a number or an integer" instead of taking the users input again.
Here's the try-catch block in the while loop:
while (true){
try{
System.out.print("Please enter a number: ");
int prime = input.nextInt();
break;
}catch (InputMismatchException IME){
System.out.println("\nNot a number or an integer!\n");
continue;
}
}
any help? thanks.
- 10-12-2010, 01:14 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
You don't say what input is.
After input has tried to read an integer (and failed) where will it try and read from next? You might want to consult the API docs for whatever class input belongs to because if it keeps repeating the message that can only be because nextInt() is repeatedly failing to return a good int.
- 10-12-2010, 01:17 AM #3
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
input is my scanner object, but I still don't understand why java doesn't read the try- portion of my code after going through the catch~ portion.
-
while (true)?
Use a boolean variable and set it in the try block after the test that sometimes causes a catch.
- 10-12-2010, 01:26 AM #5
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
What happens is that *every time* nextInt() encounters an error the continue statement makes the program go back to the start of the try block, which it faithfully does. Not just the first time but *every time* an error occurs.
(As an aside this means that what gets printed is not quite what you reported.)
Now, did you understand the point I made before: that the program behaviour indicates that nextInt() is repeatedly having an error?
What did you find in the Scanner docs?
- 10-12-2010, 01:35 AM #6
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
Well, I'm still quite new to java, so I'm having a little trouble with the Scanner docs.
But I understand when you said that nextInt() is repeatedly having an error, but all I am trying to do is make the program check if the user enters something other than an integer, so it can take the user's input again to make sure it's an integer.
In other words I'm trying prevent the user from entering anything other than an integer.
thanks for your help.
- 10-12-2010, 01:50 AM #7
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Yes, I understand what you're trying to do.
First let's look at your code with some line numbers:
Java Code:import java.util.InputMismatchException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); while(true){ try{ /*1*/ System.out.print("Please enter a number: "); /*2*/ int prime = input.nextInt(); break; } catch (InputMismatchException IME){ /*3*/ System.out.println("\nNot a number or an integer!\n"); continue; } } } }
(Well, it's my code not yours. The thing is that it's runnable so we can all talk objectively about the same thing.)
Judging from the output you are seeing (which is a constant repetition of both messages) the code is evidently travelling the route 1-2-3-1-2-3-1-2-3-1-2-3-... The big question is the second time we get to line 2, why the computer doesn't stop and wait for you to enter a new bit of input.
The Scanner docs are the key here. (as always!) Scanner never promised it would stop when you call nextInt(). Basically it reads from whereever it is. Here is an extract from the nextInt() documentation:
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
It's the last sentence that holds the solution. The scanner advances on to the next thing to scan: but only if the "translation" is successful ie only if you actually enter an int. If you don't enter a valid int then the next time you call nextInt() it will attempt to read exactly the same piece of bogus (non int) text.
What you need to do is to put in another line of code that will force the scanner to read whatever is on the current line (to "consume" it in the langauge of the docs). That way when you later call nextInt() the program will stop and wait for something to be entered. The best place for this line of code will be right after you print the "Not a number" message.
- 10-12-2010, 02:03 AM #8
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
Thanks!:D I understand what you said, however I am not sure what code I should use right after that certain point.
- 10-12-2010, 02:04 AM #9
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 785
- Rep Power
- 12
I think you should, if you can, avoid to catch runtime exceptions like this one.
In your case you could read a String (next() instead of nextInt()) and check yourself whether it is a number.
Java Code://..... int prime = readInt(input); //....... private static int readInt(Scanner input) { String s = null; boolean isNumber = false; do { System.out.print("Please enter a number: "); s = input.next(); if (!(isNumber = s.matches("\\d+"))) { System.out.println("\nNot a natural number\n"); } } while (!isNumber); return Integer.parseInt(s); }
....Just my two cents :D
- 10-12-2010, 02:14 AM #10
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
12345678901234567890123456789012345678901234567890 ?
My 2c would be "always trust the library writers, those guys are smart". If they offer a nextInt(), and they deliberately have it throw an exception under certain circumstances, I would take advantage of both of these features.
- 10-12-2010, 02:16 AM #11
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
@OP: Have you looked at each of the nextXXX() methods?
Try nextLine().
- 10-12-2010, 02:31 AM #12
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
Well, thanks for all your help, but I've found another method of doing this. I created a method to check whether the number is a number or not and I ran the function in a loop, so the try-catch block could be run again and again until the user enters an integer.:)
Java Code:import java.util.InputMismatchException; import java.util.Scanner; public class Vanilla { public static int prime; public static void main(String[] args){ while (true){ boolean T = checker(); if (T==true) break; else continue; } if (prime%2>0 && prime%3>0 && prime%4>0 && prime%5>0 && prime%6>0 && prime%7>0 && prime%8>0 && prime%9>0 || prime == 2 || prime == 3 || prime == 5 ||prime == 7){ System.out.println("The number is prime!"); }else System.out.println("The number is not prime!"); } public static boolean checker(){ Scanner input = new Scanner(System.in); try{ System.out.print("Please enter a number: "); prime = input.nextInt(); return true; }catch (InputMismatchException IME){ System.out.println("\nNot a number or an integer!\n"); return false; } } }
- 10-12-2010, 03:00 AM #13
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 785
- Rep Power
- 12
matches("([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|1([0-3][0-9]{7}|4([0-6][0-9]{6}|7([0-3][0-9]{5}|4([0-7][0-9]{4}|8([0-2][0-9]{3}|3([0-5][0-9]{2}|6([0-3][0-9]|4[0-7])))))))))")
D
Okay maybe you are right.
But I think the try catch can still be avoided. He could use input.hasNextInt() for example....
- 10-12-2010, 03:07 AM #14
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Yes hasNextInt() will avoid the try catch logic (at the cost of always checking). Now all I would require to actually do this is a convincing case for avoiding try/catch in these circumstances.
(I'm not saying you're wrong - just that I wouldn't bother in this case.)
- 10-12-2010, 03:11 AM #15
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
@OP - Sorry, I never acknowledged what you've done.
Again, it isn't how I would have done it, that's all. All the "static" stuff worries me. But the major feature is creating one Scanner instance after another. Not that this is terribly expensive in any sense, but it's not going to work if you decide to take your input from, say, a file instead of from System.in. (And that's *just* the sort of thing you might do to test the program.)
But, good luck ... and on to the next problem!
- 10-12-2010, 03:18 AM #16
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
Could you give me an example with hasNextInt() please? I would really appreciate it. Thanks again for the help
- 10-12-2010, 03:25 AM #17
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 785
- Rep Power
- 12
- 10-12-2010, 05:49 AM #18
Member
- Join Date
- Oct 2010
- Posts
- 15
- Rep Power
- 0
Similar Threads
-
how to catch two exceptions in one catch()?
By arnab321 in forum New To JavaReplies: 1Last Post: 11-06-2008, 11:54 AM -
try catch...
By MarkWilson in forum New To JavaReplies: 8Last Post: 06-27-2008, 06:39 PM -
try catch!?
By Joe2003 in forum Advanced JavaReplies: 2Last Post: 01-28-2008, 08:51 PM -
Use try and catch
By zoe in forum New To JavaReplies: 2Last Post: 07-25-2007, 08:50 PM
Bookmarks