here's my question. how do I put a string in a for statement example: for (the string being entered by user.equals(X)) do this i want this method so the statement repeats itself until that desired specific string is entered by the user
3 Answers
This shoudl totally do what you want. If user enters a name that is not equal to "Mike" then the loop will continue. Hope it helps!
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
String name = "Mike";
Scanner scan = new Scanner(System.in);
System.out.println("Enter your name: ");
String user = scan.nextLine();
while (!user.equals(name)) {
System.out.println("Enter your name: ");
user = scan.nextLine();
}
System.out.println("Good bye");
}
}
Comments
Define a key for the exit of a while loop [q in this example], and read the user input until the condition is met.
Example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to ....");
System.out.println("press \"q\" to exit or just type word until the end of the life");
String userInput =scan.nextLine();
while (!"q".equalsIgnoreCase(userInput)) {
System.out.println("The user input was: " + userInput);
System.out.println("try again please (\"q\" to exit) ");
userInput =scan.nextLine();
}
} // Ends playGame
so this code will ask the user to give an string until q in passed...
while (!user.equals(X) ) { .... }?