0

I'm working on setting up a while() that executes until the user enters an integer. However, the way I have it now, the loop prints the message "Please enter an integer" again after the integer has been entered, and then the program executes normally. Can someone suggest a way to make not print that message again after an integer has been entered? Thanks!

            System.out.println("Enter word length");
            if(in.hasNextInt())
            {    
                n = in.nextInt();
            }
            else
            {
                while(in.hasNext()) //this is the loop i'm talking about
                {
                    System.out.println("Please enter an integer");
                    if(in.hasNextInt())
                    {    
                        n = in.nextInt();
                        break;
                    }
                    else
                    {
                        String c = in.next();
                    }
                }
            }      
1
  • I changed it to while(in.hasNextLine) and now the message prints twice in the very beginning. So it doesn't solve the problem, unfortunately. Commented Apr 21, 2014 at 18:23

1 Answer 1

2

I am assuming that you want user to enter int (or Integer) and repeatedly ask user until user enters int(or Integer). If so, try this:

System.out.println("Enter word length");
if(in.hasNextInt()) {    
    n = in.nextInt();
 } else {
         while(in.hasNext()) //this is the loop i'm talking about
         {

             if(in.hasNextInt())
             {    
                 n = in.nextInt();
                 break;
             }
             else
             {
                 String c = in.next();
                 System.out.println("Please enter an integer");
             }
         }
     }      
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.