我想知道为什么当我在被问及此方法中是否还有更多数字后键入“y”时,代码可以正常工作并离开循环,但在键入“n”并按回车键后,我需要键入“n' 并再次点击返回,否则进程就会挂起。
为什么?
字符串 'input' 是从 main 方法中的用户输入传递过来的,在本例中是“addition”。
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}
我已经设法让代码通过使用
System.out.println("Any more digits? Type y/n");
String yayOrNay = scan.next();
if (yayOrNay.length()==1 && yayOrNay.charAt(0)=='y')
{
keepGoing = true;
}
但对于我来说,它所做的一切似乎有点太复杂了。
最佳答案
scan.next()
从输入流中提取一个新字符。
因此,当您检查 'n' 并执行 scan.next().matches("Y|y")
时,它实际上会跳过 'n' 进行下一次比较。
解决方案是将 scan.next()
赋值给您可以使用的变量:
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String next = scan.next();
if (next.matches("Y|y"))
{
keepGoing = true;
}
else if (next.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
关于Java:输入比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433299/