我有一個關於這個HiLo遊戲的真正快速的問題。當我去測試它時,除非我想讓它顯示他們猜測了多少次嘗試,否則一切正常。我想說的是,它不會計算最初的猜測,而是計算它後面的那個,所以它顯示的是一個比實際更少的猜測。這是我的代碼。隨機數發生器HiLo遊戲
編輯:我有另一個快速的問題。我希望程序不要猜測它是否超出了從0到10的範圍。我將如何去做,因爲當我運行程序時,它會將猜測算作我的一個嘗試。
import java.util.Random; // Random number generator class
import java.util.Scanner; // reads user inputs
public class HiLo
{
\t public static void main (String[] args)
\t {
\t \t //declare variables
\t \t final int MAX = 10;
\t \t int answer, guess;
\t \t int numberOfTries = 0 ;
\t \t String again;
\t \t Scanner Keyboard = new Scanner(System.in);
\t \t do
\t \t {
\t \t \t System.out.print (" I'm thinking of a number between 0 and "
\t \t \t + MAX + ". Guess what it is: ");
\t \t \t guess = Keyboard.nextInt();
\t \t \t //guess
\t \t \t Random generator = new Random(); //Random number generator. 0 to 10.
\t \t \t answer = generator.nextInt(MAX) +1;
\t \t \t if (guess > 10)//if guess is bigger than 10 then error message
\t \t \t {
\t \t \t System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
\t \t \t }
\t \t \t if (guess < 0)//if guess is smaller than 0 then error message
\t \t \t {
\t \t System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
\t \t \t }
\t \t \t while (guess != answer)//If guess is not the answer
\t \t \t {
\t \t \t if (guess > answer)//If guess is more than the answer
\t \t \t {
\t \t \t System.out.println ("You guessed too high! \nTry again:");
\t \t \t guess = Keyboard.nextInt();
\t \t \t }
\t \t \t if (guess < answer)//If guess is less than the answer
\t \t \t {
\t \t \t System.out.println ("Too Low! \nTry again:");
\t \t \t guess = Keyboard.nextInt();
\t \t \t }
\t \t \t numberOfTries=numberOfTries+1;
\t \t \t }//end of the loop
\t \t \t // display result
\t \t \t if (guess == answer)
\t \t \t {
\t \t \t numberOfTries += 1;
\t \t \t System.out.println ("YOU WIN!");
\t \t \t System.out.println("It took you " + numberOfTries + " tries!") ;
\t \t \t System.out.println();
\t \t \t System.out.print("Do you want to play again(Y/N)?");
\t \t \t }
\t \t \t Keyboard.nextLine(); // skip over enter key
\t \t \t again = Keyboard.nextLine();
\t \t \t numberOfTries=0;
\t \t }while (again.equalsIgnoreCase ("Y"));
\t } // end of class
} //end of main
謝謝!
我建議閱讀標籤維基以瞭解它在使用它之前是什麼。 [tag:hilo]不是爲了這個目的。 – Mephy 2014-10-20 22:11:00