我的代碼是一個猜謎遊戲:用戶就可以選擇任何5,10或20次嘗試,並有多次猜測randomNumber的動產由計算機。如果他們的猜測錯誤,我的代碼會對每個猜測進行猜測並打印出來,如果他們的猜測高於或低於randomNumber,並且他們的猜測是正確的,則打印出祝賀消息。 我需要有一個消息,說:「對不起,(用戶名),你沒有猜對幻數,(randomNumber),在(他們選擇怎麼過很多猜測)試圖」 這只是在他們使用了所有的猜測之後,仍然沒有猜到數字。 我寫我的代碼,通過我得到,說我有一個別人沒有的。如果一個錯誤,但我覺得這可能不是我唯一的問題。有人能告訴我如何在我的代碼中包含這個嗎? 這就是:試圖使用else if語句?
-2
A
回答
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,你的程序假定你已經完成了所有的陳述,並期望有新的東西開始。
在你的代碼,即「新的東西」是一個其他 - 這顯然是行不通的,因爲沒有如果說法,這可以合理訪問。
長話短說 - 當使用如果和否則,如果,你並不真的需要使用突破。大括號是大多數情況下綽綽有餘。
我希望對你有幫助。如果您還有任何問題,請打我。
相關問題
- 1. 嘗試else if語句?
- 2. if else if else語句(JS)
- 3. 使用IF/ELSE語句
- 4. If else語句
- 5. If/else語句
- 6. if else語句
- 7. 「形」 - if-else語句
- 8. jquery if else語句
- 9. Python if else語句
- 10. PHP if/else語句
- 11. if else語句php
- 12. IF ELSE語句php
- 13. if和else語句
- 14. Big if else語句
- 15. jquery if else語句
- 16. Oracle IF/ELSE語句
- 17. PHP if else語句
- 18. string.format if else語句
- 19. Pexpect if else語句
- 20. XSL if else語句
- 21. Laravel if else語句
- 22. 的if else語句
- 23. 寫if if elseif else語句
- 24. if,else if echo語句
- 25. C++ If/else if語句
- 26. 一行if..else if .. else語句
- 27. 用的if else語句
- 28. 如何在此if/else語句中添加if/else語句?
- 29. Android:調試if和else語句
- 30. 使用if ... else if ... else語句創建一個向量R
嘗試添加大括號到你的if語句。缺乏大括號可能導致Java認爲沒有相應的其他聲明,特別是因爲你的if塊是多行的。 – steph
如果您不夠自信,請勿在純文本板中編寫代碼。嘗試一個IDE。它會顯示語法檢查錯誤。 – Kent