Results 1 to 5 of 5
  1. #1
    wfsteadman is offline Member
    Join Date
    Jan 2013
    Location
    Texas
    Posts
    45
    Rep Power
    0

    Question Checking if String is added when integer required

    Greetings all,
    I have a while loop which presents me with a menu. The options the user can select are 1-6.
    I have it setup and if someone puts 10, the default switch catches it and says invalid input and the user is presented with the menu again. What I am trying to do is add something so that if they put in a String instead of an integer, that it will tell them they made an invalid entry and return them to the menu. Below is the code I have so far. What happens is they are presented with the menu and say for example if they enter "bob", then they get a message that says invalid input but the menu just keeps going in an infinite loop. This code has a try catch statement thinking that might help but I still get an infinite loop. I am just try to catch if the user does not put an integer.
    Any assistance would be appreciated. This is my first time creating a console menu.

    Wally

    Java Code:
    Scanner myScanner = new Scanner(System.in);
    
    while (true)
        {
          System.out.println("Enter the number from the selection below:\n"
                  + "1. Add new value to Array\n"
                  + "2. Find first instance of a number\n"
                  + "3. Find all instances of a number\n"
                  + "4. Delete a number\n"
                  + "5. Sort Array\n"
                  + "6. Quit");
          try{
          errorCheck = myScanner.nextInt();
          selection = errorCheck;
          }catch(Exception e)
          {
          System.out.print("Enter and integer\n");
          }
          
          switch (selection)
          {
            case 1:
              System.out.print("Case 1\n");
              break;
            case 2:
              System.out.print("Case 2\n");
              break;
            case 3:
              System.out.print("Case 3\n");
              break;
            case 4:
              System.out.print("Case 4\n");
              break;
            case 5:
              System.out.print("Case 5\n");
              break;
            case 6:
              System.out.print("Exiting Program");
              System.exit(0);
              break;
            default:
              System.out.print("Invalid Selection try again\n");
              break;
          }
        }

  2. #2
    wfsteadman is offline Member
    Join Date
    Jan 2013
    Location
    Texas
    Posts
    45
    Rep Power
    0

    Default Re: Checking if String is added when integer required

    I had to add a myScanner.nextLine(); in the catch as well as changing selection to an invalid number and now it works without looping.

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

    Default Re: Checking if String is added when integer required

    This code has a try catch statement thinking that might help but I still get an infinite loop.
    The scanner will throw an exception if it can't interpret "bob" as an integer, but it will leave "bob" in the input stream. (Details in the API docs.) Hence the infinite loop as the scanner repeatedly reads "bob" and repeatedly throws the exception.

    The solution is to read the user's input as a string (there's a scanner method for that). Then parse it yourself using Integer.parseInt(), this will also throw an exception which you can catch and respond to but at least the offending input has been read and won't be read again.

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

    Default Re: Checking if String is added when integer required

    I was too slow :(

    Yes, nextLine() will remove the offending input. Fwiw here's what I was talking about (untested) which allows for messages specific to the type of error (and also setting the input to something invalid which is maybe a little inelegant)

    Java Code:
    Scanner myScanner = new Scanner(System.in);
     
    while (true)
        {
          System.out.println("Enter the number from the selection below:\n"
                  + "1. Add new value to Array\n"
                  + "2. Find first instance of a number\n"
                  + "3. Find all instances of a number\n"
                  + "4. Delete a number\n"
                  + "5. Sort Array\n"
                  + "6. Quit");
          try{
              selection = Integer.parseInt(myScanner.nextLine());
          }catch(NumberFormatException nfe)
          {
              System.out.print("Your input must be an integer!  Try again...\n");
              continue;
          }
           
          switch (selection)
          {
            case 1:
              System.out.print("Case 1\n");
              break;
            case 2:
              System.out.print("Case 2\n");
              break;
            case 3:
              System.out.print("Case 3\n");
              break;
            case 4:
              System.out.print("Case 4\n");
              break;
            case 5:
              System.out.print("Case 5\n");
              break;
            case 6:
              System.out.print("Exiting Program");
              System.exit(0);
              break;
            default:
              System.out.print("Invalid Selection try again\n");
              break;
          }
        }

  5. #5
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    7

    Default Re: Checking if String is added when integer required

    I think it is better to use the validation methods that already provided by the scanner class such as the hhasNextInt(). For example using the snippet below:

    Java Code:
            int number;
            do {
                System.out.println("Please enter a positive number: ");
                while (!scanner.hasNextInt()) {
                    String input = scanner.next();
                    System.out.printf("\"%s\" is not a valid number.\n", input);
                }
                number = scanner.nextInt();
            } while (number < 0);

Similar Threads

  1. Replies: 2
    Last Post: 09-24-2012, 11:31 PM
  2. checking for quotes in a string
    By kilyx in forum New To Java
    Replies: 3
    Last Post: 12-15-2011, 12:06 AM
  3. Checking The Contents of a String
    By jayragz in forum New To Java
    Replies: 7
    Last Post: 05-26-2011, 10:15 AM
  4. Checking If A String Contains Symbols
    By SwissR in forum New To Java
    Replies: 7
    Last Post: 07-27-2010, 09:07 AM
  5. Help with checking for a certain format in a String
    By SteroidalPsycho in forum New To Java
    Replies: 2
    Last Post: 03-26-2010, 04:56 AM

Posting Permissions

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