我遇到了一个问题,即Scanner在无限期循环期间没有阻止用户输入。我尝试过使用hasNextLine()
但是没有用。它只是无限地运行循环调用displayMenu()
。
do {
displayMenu();
int response;
while (iStream.hasNextLine()) {
response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
}
while (!done);
我也尝试过不使用hasNextLine()
,但我最终得到NoSuchElementException
,因为它第一次运行完美,但在第二次迭代时,它不会阻止用户输入。< / p>
do {
displayMenu();
int response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
while (!done);
有什么想法吗?
答案 0 :(得分:0)
以下对我来说很好:
private static void displayMenu ()
{
System.out.println ("Menu:");
System.out.println ("\t1: Decode message");
System.out.println ("\t2: Encode message");
System.out.println ("\t3: Display alphabet");
System.out.println ("\t4: Exit");
}
public static void main (String [] args)
{
Scanner scanner = new Scanner (System.in);
boolean done = false;
while (!done)
{
displayMenu();
switch (Integer.parseInt (scanner.nextLine ()))
{
case 1:
System.out.println ("Decoding...");
break;
case 2:
System.out.println ("Encoding...");
break;
case 3:
System.out.println ("Displaying alphabet...");
break;
case 4:
System.out.println("Exitting...");
done = true;
break;
default:
done = false;
}
}
}