You are reading from the Scanner object using the method nextInt(). Do you know what nextInt() does when the user enters something else than a valid number, such as the letter 'q'? From the API 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.
So, an InputMismatchException is thrown when the user enters 'q'. If you don't want this, use a method like nextLine() instead, and check if it contains 'q' before converting it to an integer yourself (which you can do with Integer.parseInt()).
Scanner in = new Scanner(System.in); do{ System.out.print("Enter an integer: "); String answer = in.nextLine; }while(answer != "q") System.out.prinln("Application Terminated");
i believe this would be much easier....
Jeff Albertson
Ranch Hand
Joined: Sep 16, 2005
Posts: 1780
posted
0
Originally posted by Jesper de Jong: So, an InputMismatchException is thrown when the user enters 'q'. If you don't want this, use a method like nextLine() instead, and check if it contains 'q' before converting it to an integer yourself (which you can do with Integer.parseInt()).
Whilst this is true, one of the annoying things about parsing methods like Integer.parseInt is that you can't look before you leap -- if the next token is not an int you have to handle this in a catch block instead of in normal code flow. On the other hand, Scanner has methods like hasNextInt which is true iff a call to nextInt would succeed at this point, so that you can encorporate this test into normal code flow. Try it!
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
9
posted
0
Originally posted by Justin bob: Scanner in = new Scanner(System.in); do{ System.out.print("Enter an integer: "); String answer = in.nextLine; }while(answer != "q") System.out.prinln("Application Terminated");
i believe this would be much easier....
Use equals() to compare Strings
Joanne
Jeff Albertson
Ranch Hand
Joined: Sep 16, 2005
Posts: 1780
posted
0
Yes, that code needs help -- it doesn't even compile...