在用户在Java上进行正确输入之前,如何循环播放? [英] How do I loop until the user makes correct input on Java?

查看:77
本文介绍了在用户在Java上进行正确输入之前,如何循环播放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.Scanner;

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

    Scanner input = new Scanner(System.in);
    String secret = "Please", guess;

    System.out.print( "Secret word?" );
    guess = input.next();

    for (int i = 0; guess.equals(secret); i++) {
      if( guess.equals(secret) ) {
        System.out.println("enter");
      } else {
        System.out.println( "try again" );
      }
    }
  }
}

我如何做到这一点,以便当用户输入请"以外的任何内容时,它会要求他/她再试一次?然后,用户将必须输入"Please",结束循环并打印"Enter".

How do I make it so that, when a user enters anything other than "Please", it will ask him/her to try again? Then the user will have to enter "Please", end the loop, and print "Enter".

推荐答案

使用while循环,

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();
    }
}

除此之外,for循环具有以下语法,

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++)

由于这种情况永远不会在第一个循环中成立,因此您根本不会进入for循环.

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

您还可以使用使用后期测试的do-while,

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

这篇关于在用户在Java上进行正确输入之前,如何循环播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆