关于这个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
谢谢!
最佳答案
您应该在if(guess == answer)中放入numberOfTries + = 1,这样它也可以计算出正确的答案
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/