我有一个关于这个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
&#13;
谢谢!
答案 0 :(得分:1)
你应该把numberOfTries + = 1放在if(guess == answer)里面,这样它也会计算正确的答案
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)?");
}
答案 1 :(得分:0)
初始化并将其重置时,应将numberOfTries设置为1,这样在进入while (guess != answer )
循环之前已经考虑了第一个猜测