java在while循环中遇到问题,并试图通过按字母来终止程序
我的程序有问题
该程序是一个HILO游戏,要求用户在生成的数字范围内猜测一个数字
问题是,一旦我在键盘上按0,它就会显示随机数,基本上必须结束循环并询问用户是想继续还是结束程序。相反,它继续循环,每当我按下键盘上的一个字母时,它就会显示一个Exception
错误,该错误描述并输入未匹配。有人能告诉我怎么修吗?,也许我把程序写错了,我尝试了多种方法,但它仍然不能正常工作。
多谢各位
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
# 1 楼答案
编辑1:
这段代码非常适合我,我试过运行它:
请复制粘贴代码。因为它毫无例外地工作得很好
我的示例输出:
示例1:
样本2:
如果有什么问题一定要告诉我
# 2 楼答案
小小的修改
# 3 楼答案
如果你想结束一个循环,你可以使用
break;
命令。它跳出while
或for
循环。如果数字是0,你可以用这个:并加上:
if(choice == "y") {break;}
到while(!Loop)
循环的最末端当答案正确时,将
Loop
设置为false,这意味着!Loop
将计算为true。当他们决定继续游戏时,你应该将Loop = false
改为Loop = true