我想知道为什么当我被问到在这个方法中是否有更多的数字时,输入'y'代码能够正常工作并且离开循环,但是当输入'n'并且返回时,我需要键入'n'并再次返回,否则该过程就会挂起。Java:输入比较
为什么?
字符串'input'从主方法的用户输入中传递,在此情况下为“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;
}
工作,但似乎有点太复杂,我为所有它在做什么。
辉煌,所有答复,谢谢,我现在明白我在那里混错! – hamc17