Azil
Azil

Reputation: 31

Java "for" statement iteration based on a string

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

Answers (3)

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

Upvotes: 1

HenryDev
HenryDev

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

Naman
Naman

Reputation: 31858

I guess

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

shall help you.

Upvotes: 0

Related Questions