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.
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
}
}
Use a do...while
loop:
guess = "";
do {
System.out.print("What is your guess? ");
guess = input.next();
} while (guess.trim().length() == 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.