这是前一个问题的延续,我无法得到答案。问题是当我尝试使用带有switch语句和“End”关键字和case的System.exit(0)方法结束程序时,代码不再按原样运行,现在只读取每秒的整数输入电脑。 这是我的方法不再有效:
public static int[] ourGuess() {
int[] guessed = new int[4];
Scanner scan = new Scanner(System.in);
System.out.println("Take your guess:");
switch (scan.nextLine()) {
case "End":
System.exit(0);
break;
}
guess = scan.nextInt();
int mod = 10;
int div = 1;
for (int i = 3; i >= 0; i--) {
int num = (guess % mod) / div;
guessed[i] = num;
div = div * 10;
mod = mod * 10;
}
return guessed;
}
该类是mastermind游戏的java实现。谢谢你的帮助!
答案 0 :(得分:1)
您正在阅读Scanner
中的两个值。
首先,您使用scan.nextLine()
读取一个值,然后放弃该值并使用scan.nextInt()
读取另一个值。
您需要保存读取的值并重复使用它:
final String line = scan.nextLine();
if(line.equals("End")) {
return guessed;
}
final int guessed = Integer.parseInt(line);
您也不应该致电System.exit
。
答案 1 :(得分:0)
首先,您不应该对一个案例使用switch语句。此外,如果读取的行不是"结束"但是一个int,你正在跳过那一个。尝试:
String next = scan.nextLine();
if(next.equalsIgnoreCase("End")) System.exit(0);
然后检查next是否是猜测的实际int,否则读取下一个int。
答案 2 :(得分:0)
通过调用nextLine()
和nextInt()
,您正在从流中读取两件事。相反,缓存nextLine()
:
String line = scan.nextLine();
switch (line) { ...}
然后以下列方式使用它:
guess = Integer.parseInt(line);