用户输入以在 Java 中重复程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26367626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:23:02  来源:igfitidea点击:

User input to repeat program in Java

javaloopsuser-input

提问by Mac

I am writing a simple guessing game program where the user will input a number to try and guess a randomly generated number.

我正在编写一个简单的猜谜游戏程序,用户将输入一个数字来尝试猜测一个随机生成的数字。

If they get the number right I want to give them the option to play again.

如果他们得到正确的号码,我想给他们再次播放的选项。

Here is my code:

这是我的代码:

public class GuessingGame {
    private Random num = new Random();       
    private int answer = num.nextInt(10);   
    private int guess;  
    private String playAgain;  

    public void inputGuess(){
        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        Scanner input = new Scanner(System.in);
        guess = input.nextInt(); 
        do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        }while (guess != answer);

        System.out.println("Congratulations, You guessed the number!");
        System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
        playAgain = input.nextLine();
        if(playAgain == "Y" || playAgain == "y"){
            System.out.println("Enter a number between 1 and 10 as your first guess: ");
            guess = input.nextInt(); 
        }

    }
}

The game plays through but when the user is prompted to play again nothing happens?

游戏玩完了,但当提示用户再次玩时什么也没有发生?

Any suggestions?

有什么建议?

采纳答案by user2494817

Here is the completed code, fully working and tested... without using recursion.. and everything fixed.

这是完整的代码,完全工作和测试......没有使用递归......一切都修复了。

    public static void main(String[] args)
    {
    String playAgain = "";
    Scanner scan = new Scanner(System.in);

    do
    {
        ClassName.inputGuess();
        System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
        playAgain = scan.nextLine();
    }
    while(playAgain.equalsIgnoreCase("Y"));
    System.out.println("Thanks for playing!");
}

public void inputGuess()
{
    Random num = new Random();
    int answer = num.nextInt(10)+1;
    Scanner input = new Scanner(System.in);
    int guess;

    System.out.println("Enter a number between 1 and 10 as your first guess: ");
    guess = input.nextInt(); 

    do
    {
        if (guess < 1 || guess > 10)
        {
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }
        else 
            if (guess > answer)
            {
                System.out.println("Too high, Try Again: ");
                guess = input.nextInt();
            }
            else 
                if (guess < answer)
                {
                    System.out.println("Too low, Try Again: ");
                    guess = input.nextInt();
                }
        input.nextLine();

    }
    while (guess != answer);

    System.out.println("Congratulations, You guessed the number!");
}

回答by Kick Buttowski

one issue:

一期

Do not compare the content of two strings by ==which just you should use equals()

不要比较==你应该使用的两个字符串的内容equals()

Imagine the right answer is one in this case

想象一下,在这种情况下,正确答案是一个

Follow this as your blue print sample

将此作为您的蓝图样本

  int answer = 0;
  String yes = "";
  Scanner input = new Scanner(System.in);
  do{
    do{
        System.out.println("Enter your number");
        answer = input.nextInt();
  } while ( answer != 1);
      System.out.println("Would you like to play again?");
      yes = input.next();
  } while ( yes.equalsIgnoreCase("yes"));

output:

输出:

enter image description here

在此处输入图片说明

回答by Rafael R. S. Robles

Here is the code:

这是代码:

private Random num = new Random();

private int answer = num.nextInt(10) +1;

private int guess;

private String playAgain;

Scanner input = new Scanner(System.in);

public void inputGuess(){
    System.out.println("Enter a number between 1 and 10 as your first guess: ");

    guess = input.nextInt();
    do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        if(guess == answer) {
            System.out.println("Congratulations, You guessed the number!");
            System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
            playAgain = input.nextLine();
        }

    }while (!playAgain.equals("Y") && !playAgain.equals("y"));
}

You just need to introduce the winning/losing logic inside the while, and the condition will be the ending/continue flag.

您只需要在 while 中引入输赢逻辑,条件将是结束/继续标志。

Another thing is always remember when comparing strings to use the equalsmethod, since the == will compare the object reference and not the String value, in some cases == will return true for equal string since how JVM stores the Strings, but to be sure always use equals.

另一件事是在比较字符串以使用equals方法时始终记住,因为 == 将比较对象引用而不是字符串值,在某些情况下 == 将为相等的字符串返回 true,因为 JVM 存储字符串的方式,但要当然总是使用equals

回答by brso05

Try something like this:

尝试这样的事情:

public void inputGuess(){
        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        Scanner input = new Scanner(System.in);
        guess = input.nextInt();
        playAgain = "Y";
        do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        if(guess == answer)
        {
            System.out.println("Congratulations, You guessed the number!");
            System.out.println("Would you like to play again? Enter Y to play or N to quit: ");
            input.nextLine();
            playAgain = input.next();
            answer = num.nextInt(10);
            guess = -1;
            if(!playAgain.equalsIgnoreCase("N"))
            {
                System.out.println("Enter a number between 1 and 10 as your first guess: ");
                guess = input.nextInt();
            }
        }

        }while (!playAgain.equalsIgnoreCase("N"));

    }

You need your code for checking if they want to play again inside the loop. This way you wait until they have guessed the number correctly then ask if they want to play again. If they do you restart the process if they don't you exit the loop.

您需要您的代码来检查他们是否想在循环内再次播放。这样你就可以等到他们猜对了数字,然后再问他们是否想再玩一次。如果他们这样做,则如果他们不这样做,则重新启动该过程,则退出循环。

回答by Alvin Bunk

Some of the solution I see above aren't correct. The random number, you need to add 1 to get between 1 and 10, also you need to compare with equals. I use case insensitive here.

The following code works as you need it.

我在上面看到的一些解决方案是不正确的。随机数,你需要加1才能得到1和10之间,还需要与equals进行比较。我在这里不区分大小写。

以下代码可根据需要工作。

import java.util.Random;
import java.util.Scanner;

public class Test2 {
    private static Random num = new Random();
    private static int answer = 0;
    private static int guess;
    private static String playAgain;

    public static void main(String[] args) {
        inputGuess();
    }

    // Guess Method.
    public static void inputGuess(){
        // create answer.
        answer = 1+ num.nextInt(10);

        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        Scanner input = new Scanner(System.in);
        guess = input.nextInt(); 
        do{
        if (guess < 1 || guess > 10){
            System.out.println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        }else if (guess > answer){
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        }else if (guess < answer){
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

        }while (guess != answer);

        System.out.println("Congratulations, You guessed the number!");
        System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
        playAgain = input.nextLine();
        if( playAgain.equalsIgnoreCase("Y") ){ 
            inputGuess();
        }

    }
}

回答by afzalex

Do the following and your code will work :

执行以下操作,您的代码将起作用:

  1. Replace all input.nextInt();with Integer.parseInt(input.nextLine());
  2. Replace (playAgain == "Y" || playAgain == "y")with (playAgain.equalsIgnoreCase("Y"))
  3. Initialise answerinside inputGuess()in starting instead.
  4. Replace the bodyof if(playAgain.equalIgnoreCase("Y"))with inputGuess();
  1. 全部替换input.nextInt();Integer.parseInt(input.nextLine());
  2. 替换(playAgain == "Y" || playAgain == "y")(playAgain.equalsIgnoreCase("Y"))
  3. 而是在启动answer里面初始化inputGuess()
  4. 更换机身if(playAgain.equalIgnoreCase("Y"))inputGuess();

When you enter integer value through console it also contain a \n(next line) in it. But when you use nextInt(), it doesn't read this \n, but then when you tried to get next line with input.nextLine(), it looks for \n(next line) which is already there from integer entry and having nothing after that. Code look for "Y" or "y" and breaks because it doesn't found any of them.

当您通过控制台输入整数值时,它还包含一个\n(下一行)。但是当您使用 时nextInt(),它不会读取 this \n,但是当您尝试使用 获取下一行时input.nextLine(),它会\n从整数条目中查找已经存在的(下一行),之后没有任何内容。代码查找“Y”或“y”并中断,因为它没有找到任何一个。

That is why Integer.parseInt(input.nextLine());works here

这就是为什么Integer.parseInt(input.nextLine());在这里工作

回答by Tirath

By now, you would have already guessed the right way to do it. Here is how I will approach it

到现在为止,您应该已经猜到了正确的方法。这是我将如何处理它

public class Test {
    public static void main (String...a) {
        inputGuess();
    }
    public static void inputGuess() {

        Scanner input = new Scanner(System.in);
        String playAgain = "Y";
        int guess;
        Random ran = new Random();
        int answer = ran.nextInt(10) + 1;
        while (playAgain.equalsIgnoreCase("Y")) {
            System.out.println("Enter a number between 1 and 10 as your first guess: " + answer);
            guess = input.nextInt(); 
            do {
                if (guess < 1 || guess > 10) {
                    System.out.println("That is not a valid entry. Please try again: ");
                    guess = input.nextInt();
                } else if (guess > answer) {
                    System.out.println("Too high, Try Again: ");
                    guess = input.nextInt();
                } else if (guess < answer) {
                    System.out.println("Too low, Try Again: ");
                    guess = input.nextInt();
                }
            } while (guess != answer);

            System.out.println("Congratulations, You guessed the number!");
            System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
            input.nextLine();
            playAgain = input.nextLine();
            answer = ran.nextInt(10) + 1
        }           
    }
}

回答by madhu_karnati

This code can serve your purpose...

此代码可以满足您的目的...

import java.util.Random;
import java.util.Scanner;

public class GuessingGame 
{
private Random num = new Random();
private int answer ;
private int guess;
private String playAgain;

public void inputGuess() 
{         
    answer = num.nextInt(11);
    System.out.println("Enter a number between 1 and 10 as your first guess: ");
    Scanner input = new Scanner(System.in);
    guess = input.nextInt();
    do {            
        if (guess < 1 || guess > 10) {
            System.out
                    .println("That is not a valid entry. Please try again: ");
            guess = input.nextInt();
        } else if (guess > answer) {
            System.out.println("Too high, Try Again: ");
            guess = input.nextInt();
        } else if (guess < answer) {
            System.out.println("Too low, Try Again: ");
            guess = input.nextInt();
        }

    } while (guess != answer);

    System.out.println("Congratulations, You guessed the number!");
    System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
    do
    {           
        playAgain = input.nextLine();

    }while(playAgain.length()<1);

    if (playAgain.trim().equalsIgnoreCase("y"))
    {
        inputGuess();           
    }
    else
    {
        System.out.println("Good Bye!!!");
    }

}

public static void main(String[] args) {
    new GuessingGame().inputGuess();
}
   }