1

sorry if this is a silly question but I am looking for a way to break and start another iteration of the loop if the user's input is null. Here's my code:

while(true) {
    // Get the users input
    Scanner Input = new Scanner(System.in);
    System.out.println("Enter text:");
    String studentInfo = Input.nextLine();

    if (studentInfo == null) {
        System.out.println("Please enter valid infomation.");
        break;
    }
    continue;
}

After the break, I want it to go back to the while(true) and start again from there, by asking the user for an input again.

Thanks guys,

JT

5
  • 4
    Note that nextLine() can never return null. Commented Oct 7, 2013 at 19:55
  • 1
    why do you need break than? Commented Oct 7, 2013 at 19:55
  • Aw okay, I didn't know that, I'm just trying to stop my code from crashing when the user just hits enter with no actual input, thanks guys though! Commented Oct 7, 2013 at 19:58
  • It is the intrinsic nature of (infinite) loops to start another iteration when the previous has finished. So no need for a break there. Commented Oct 7, 2013 at 20:00
  • I know but what I'm trying to achieve was to not come up an error message when an empty input was used, instead just print a statement and carry on with the iteration. I have been answered now though so thank you! Commented Oct 7, 2013 at 20:03

1 Answer 1

4

Check for:

if (studentInfo.isEmpty()) {
    continue;
}

Remove the Scanner input = new Scanner(System.in); declaration from inside the while loop.

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.