gpt4 book ai didi

java - 带随机数生成器的 HiLo 游戏

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

我有一个关于这款 HiLo 游戏的快速问题。当我去测试它时,一切正常,除非我希望它显示他们猜测了多少次尝试。我想说的是,它不计算最初的猜测,而是计算其后的猜测,因此它显示的猜测比实际的猜测少一个。这是我的代码。

编辑:我还有另一个简单的问题。如果超出 0 到 10 的范围,我希望程序不要计算猜测值。我将如何执行此操作,因为当我运行程序时,它将猜测值算作我的尝试之一。

import java.util.Random;     // Random number generator class
import java.util.Scanner; // reads user inputs

public class HiLo
{
public static void main (String[] args)
{
//declare variables
final int MAX = 10;
int answer, guess;
int numberOfTries = 0 ;
String again;

Scanner Keyboard = new Scanner(System.in);

do

{
System.out.print (" I'm thinking of a number between 0 and "
+ MAX + ". Guess what it is: ");
guess = Keyboard.nextInt();
//guess
Random generator = new Random(); //Random number generator. 0 to 10.
answer = generator.nextInt(MAX) +1;

if (guess > 10)//if guess is bigger than 10 then error message
{
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
}
if (guess < 0)//if guess is smaller than 0 then error message
{
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
}

while (guess != answer )//If guess is not the answer
{

if (guess > answer )//If guess is more than the answer
{
System.out.println ("You guessed too high! \nTry again:");
guess = Keyboard.nextInt();
}

if (guess < answer )//If guess is less than the answer
{
System.out.println ("Too Low! \nTry again:");
guess = Keyboard.nextInt();
}

numberOfTries=numberOfTries+1;

}//end of the loop

// display result
if ( guess == answer)
{
numberOfTries += 1;
System.out.println ("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!") ;
System.out.println();
System.out.print( "Do you want to play again(Y/N)?");
}


Keyboard.nextLine(); // skip over enter key
again = Keyboard.nextLine();

numberOfTries=0;



}while (again.equalsIgnoreCase ("Y") );



} // end of class

} //end of main

谢谢!

最佳答案

你应该将 numberOfTries += 1 放在 if (猜测==答案) 中,这样它也会计算正确答案

if ( guess == answer)
{
numberOfTries += 1; // <--- This adds the final guess
System.out.println ("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!") ;
System.out.println();
System.out.print( "Do you want to play again(Y/N)?");
}

关于java - 带随机数生成器的 HiLo 游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475570/

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