1

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

1
  • 1
    have you tried while (!user.equals(X) ) { .... } ? Commented Apr 9, 2016 at 21:17

3 Answers 3

1

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");

 }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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...

Comments

0

I guess

for( ; !user.equals(X) ;)
  { user = <scanner input> ;  //accept a scanner input  }

shall help you.

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.