Reputation: 31
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
Upvotes: 1
Views: 77
Reputation: 48258
Define a key
for the exit of a while loop [q in this example], and read the user input until the condition is met.
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...
Upvotes: 1
Reputation: 4953
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");
}
}
Upvotes: 1
Reputation: 31858
I guess
for( ; !user.equals(X) ;)
{ user = <scanner input> ; //accept a scanner input }
shall help you.
Upvotes: 0