2016-12-06 66 views
-2

我的代碼是一個猜謎遊戲:用戶就可以選擇任何5,10或20次嘗試,並有多次猜測randomNumber的動產由計算機。如果他們的猜測錯誤,我的代碼會對每個猜測進行猜測並打印出來,如果他們的猜測高於或低於randomNumber,並且他們的猜測是正確的,則打印出祝賀消息。 我需要有一個消息,說:「對不起,(用戶名),你沒有猜對幻數,(randomNumber),在(他們選擇怎麼過很多猜測)試圖」 這只是在他們使用了所有的猜測之後,仍然沒有猜到數字。 我寫我的代碼,通過我得到,說我有一個別人沒有的。如果一個錯誤,但我覺得這可能不是我唯一的問題。有人能告訴我如何在我的代碼中包含這個嗎? 這就是:試圖使用else if語句?

+2

嘗試添加大括號到你的if語句。缺乏大括號可能導致Java認爲沒有相應的其他聲明,特別是因爲你的if塊是多行的。 – steph

+3

如果您不夠自信,請勿在純文本板中編寫代碼。嘗試一個IDE。它會顯示語法檢查錯誤。 – Kent

回答

0

這將幫助你。

for(int i = 1; i <= numberOfGuesses; i++){ 
    System.out.print("Enter guess #"+i+": "); 
    guess = scan.nextInt(); 
     if (guess > randomNumber) 
        System.out.println("Your guess, "+guess+", is greater than the magic number."); 
     else if (guess < randomNumber) 
        System.out.println("Your guess, "+guess+" is less than the magic number."); 
     else if (guess == randomNumber){ 
        System.out.println("Congratulations, "+name+"! You guessed the magic number in "+i+" guesses."); 
        break; 
       } 
     if (i == numberOfGuesses) 
      System.out.println("Sorry, "+ name+"you did not guess the magic number,"+ randomNumber+"in"+numberOfGuesses+ "tries."); 

    } 

輸出:

Please enter your name: user 
Would you like to try to guess a number? (Yes or No):yes 
How many guesses would you like? (5, 10, 20)5 
Enter guess #1: 1 
Your guess, 1 is less than the magic number. 
Enter guess #2: 100 
Your guess, 100, is greater than the magic number. 
Enter guess #3: 2 
Your guess, 2 is less than the magic number. 
Enter guess #4: 3 
Your guess, 3 is less than the magic number. 
Enter guess #5: 4 
Your guess, 4 is less than the magic number. 
Sorry, useryou did not guess the magic number,71in5tries. 
0

錯誤就出在這裏:

break; 

當使用突破,則如果語句被取消。這就是你得到這個錯誤的原因。

想想它的第二個:

你把一個如果聲明與幾個否則,如果是事後

當你說break,你的程序假定你已經完成了所有的陳述,並期望有新的東西開始。

在你的代碼,即「新的東西」是一個其他 - 這顯然是行不通的,因爲沒有如果說法,這可以合理訪問。

長話短說 - 當使用如果否則,如果,你並不真的需要使用突破。大括號是大多數情況下綽綽有餘。

我希望對你有幫助。如果您還有任何問題,請打我。