我的代码是一个猜谜游戏:用户就可以选择任何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. 试图在对象中使用for循环if else else语句
- 2. 尝试else if语句?
- 3. if else if else语句(JS)
- 4. 使用if和else语句
- 5. PHP:使用IF ELSE语句
- 6. 使用IF/ELSE语句
- 7. 使用if else语句
- 8. if/else语句
- 9. If else语句
- 10. if else语句
- 11. if-else语句
- 12. If/else语句
- 13. 试图让我的计划继续使用if/else语句C++
- 14. jquery if else语句
- 15. Big if else语句
- 16. IF ELSE语句SQLite
- 17. Python if else语句
- 18. jQuery if/else语句
- 19. PHP if/else语句
- 20. “形” - if-else语句
- 21. 的if else语句
- 22. PHP IF ELSE语句
- 23. PHP - if ... else ...语句
- 24. VHDL If/Else语句
- 25. jquery if else语句
- 26. string.format if else语句
- 27. hash.indexOf()if else语句
- 28. Oracle IF/ELSE语句
- 29. JQuery Else if语句?
- 30. Laravel if else语句
尝试添加大括号到你的if语句。缺乏大括号可能导致Java认为没有相应的其他声明,特别是因为你的if块是多行的。 – steph
如果您不够自信,请勿在纯文本板中编写代码。尝试一个IDE。它会显示语法检查错误。 – Kent