Home > OS >  How to check if value is entered, and if nothing is entered reprompt them
How to check if value is entered, and if nothing is entered reprompt them

Time:12-22

I want to use a while loop to check if the user entered their guess and if nothing was entered reprompt them to enter it. I am new to Java sorry if this is really obvious.


            System.out.println("What is your guess? ");
            guess = input.next();

I tried to use while(guess != null), but it didn't work.

CodePudding user response:

import java.util.Scanner;  // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);  // Create a Scanner object
System.out.println("What is your guess? "); //
String userName = myObj.nextLine();  // Read user input
System.out.println("Username is: "   userName);  // Output user input
}
}

CodePudding user response:

Use a do...while loop:

guess = "";
do {
    System.out.print("What is your guess? ");
    guess = input.next();
} while (guess.trim().length() == 0);
  • Related