How do I loop until the user makes correct input on Java?

后端 未结 4 1149
囚心锁ツ
囚心锁ツ 2020-12-20 05:08
import java.util.Scanner;

public class SecretWord {
  public static void main( String[] args ) {

    Scanner input = new Scanner(System.in);
    String secret = \"         


        
4条回答
  •  再見小時候
    2020-12-20 05:44

    Use a while loop instead,

    while (!guess.equals(secret)) {
        if( guess.equals(secret) ) {
            System.out.println( "enter" );
        } else {
            System.out.println( "try again" ); {
            System.out.println("Secret word")
            guess = input.next();
        }
    }
    

    Apart from this, the for loop have the following syntax,

    for (before, conditionsIsTrue, end)
    

    This means that for you the loop will be like this,

    for(int i=0; if(guess.equals(secret)), i++)
    

    Since this condition will never hold for the first loop you will never enter the for loop at all.

    You can also use do-while which uses a post test,

    do {
        System.out.println("Secret word")
        guess = input.next();
        if( guess.equals(secret) ) {
            System.out.println( "enter" );
        } else {
            System.out.println( "try again" ); {
        }
    } while (!guess.equals(secret));
    

提交回复
热议问题