Results 1 to 18 of 18
  1. #1
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

    Exclamation 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.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    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.

  3. #3
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

    Default

    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.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    while (true)?

    Use a boolean variable and set it in the try block after the test that sometimes causes a catch.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    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?

  6. #6
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

    Default

    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.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    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.

  8. #8
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

    Default

    Thanks!:D I understand what you said, however I am not sure what code I should use right after that certain point.

  9. #9
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    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);
    	}
    one advantage is that you can allow only natural numbers(a prime can only be a natural number)...

    ....Just my two cents :D

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    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.

  11. #11
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    @OP: Have you looked at each of the nextXXX() methods?

    Try nextLine().

  12. #12
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

    Default

    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;
    		}
    	}
    }

  13. #13
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    Quote Originally Posted by pbrockway2 View Post
    12345678901234567890123456789012345678901234567890 ?
    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....

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    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.)

  15. #15
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    @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!

  16. #16
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

    Default

    Could you give me an example with hasNextInt() please? I would really appreciate it. Thanks again for the help

  17. #17
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    Quote Originally Posted by themulator View Post
    Could you give me an example with hasNextInt() please? I would really appreciate it. Thanks again for the help
    With the code from your first post:
    Java Code:
    		while (true) {
    				System.out.print("Please enter a number: ");
    				if(input.hasNextInt()){
    					int prime = input.nextInt();
    					break;
    				}
    				else{
    					System.out.println("\nNot a number or an integer!\n");
    					input.next(); // :-)
    				}
    		}
    :p

  18. #18
    themulator is offline Member
    Join Date
    Oct 2010
    Posts
    15
    Rep Power
    0

Similar Threads

  1. how to catch two exceptions in one catch()?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 11-06-2008, 10:54 AM
  2. try catch...
    By MarkWilson in forum New To Java
    Replies: 8
    Last Post: 06-27-2008, 05:39 PM
  3. try catch!?
    By Joe2003 in forum Advanced Java
    Replies: 2
    Last Post: 01-28-2008, 07:51 PM
  4. Use try and catch
    By zoe in forum New To Java
    Replies: 2
    Last Post: 07-25-2007, 07:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •