gpt4 book ai didi

java - 猜谜游戏范围

转载 作者:行者123 更新时间:2023-12-01 11:55:08 24 4
gpt4 key购买 nike

我已经完成了类作业,除了一件事还没有弄清楚。我怎样才能让程序只允许1到100范围内的数字?如果用户输入一个小于1或大于100的数字,它应该告诉用户该数字超出范围。

我设置了一个随机类和一个 while 循环,它接受输入并告诉用户数字过高或过低。如果数字正确,则显示您赢得按摩。一切正常,但只有范围部分。 导入java.util.Scanner;导入 java.util.Random;

公共(public)课 GuessingGame {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Random generator = new Random();
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 0;

Scanner input = new Scanner (System.in);
int guess;
boolean win = false;


System.out.println("You have 10 tries to guess a number between 1 and 100");

while(!win && numberOfTries < 10)
{
System.out.println("Guess a number: ");
guess = input.nextInt();

if (guess < 1 || guess > 100)
{
System.out.println("Guess is out of range!");
continue;
}


if (guess == numberToGuess)
{
win=true;
}

else if (guess < numberToGuess)
{
System.out.println("Your guess is too low");
}
else if (guess > numberToGuess)
{
System.out.println("Your guess is too high");
}

}

System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + numberOfTries + " tries." );


}

}- 我添加了其余的代码 -

但是如果我输入像-1或101这样的数字,程序会说数字太高或数字太低,忽略超出范围的语句。不明白为什么。请你帮助我好吗?谢谢

最佳答案

我对您的代码添加了一些改进:

numberOfTries++ 检查有效范围后,因为需要增加这个数字,否则循环在猜测 10 次后不会结束。

break 当玩家获胜时,因为您不希望循环在这种情况下继续。

循环结束后,您需要检查玩家是否获胜。也有可能他猜了10次都没有中奖。

我认为现在它应该按预期工作。

public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 0;

Scanner input = new Scanner (System.in);
int guess;
boolean win = false;

System.out.println("You have 10 tries to guess a number between 1 and 100");

while(!win && numberOfTries < 10)
{
System.out.println("Guess a number: ");
guess = input.nextInt();

if (guess < 1 || guess > 100)
{
System.out.println("Guess is out of range!");
continue;
}

// increase numberOfTries by 1 because player made another valid guess
numberOfTries++;

if (guess == numberToGuess)
{
win=true;
// exit the while loop because player won
break;
}

if (guess < numberToGuess)
{
System.out.println("Your guess is too low");
}
else
{
// guess must be > numberToGuess here
System.out.println("Your guess is too high");
}
}

if(win)
{
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + numberOfTries + " tries." );
}
else
{
System.out.println("Sorry, you didn't win.");
System.out.println("The right number was " + numberToGuess);
}
}

关于java - 猜谜游戏范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28515501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com