java为什么我的while循环只对某些嵌套的“if”语句有效,而对其他语句无效?
while循环应该询问用户想要选择哪个选项,选项完成后,应该返回while循环的开始。现在,它只对第二个else if
正确工作,其他什么都没有
while(flag){
System.out.println("Select an option from the menu below:" +
"\n1: Display consecutive numbers in a right triangle" + //needs better explanation
"\n2: Determine if a number is divisible by 3" +
"\n3: Determine the number of periods and spaces in a string" +
"\n4: Display a right triangle of astrisks" +
"\n5: Exit"); //better explanation
String option = input.nextLine();
if(option.equals("1")){ //does not work
System.out.println("Enter number of columns: ");
int width = input.nextInt();
while(width<=0 || width%1!=0){
System.out.println("Invalid input! Please enter a positive width.");
width = input.nextInt();
}
numOfColumns(width);
}
else if(option.equals("2")){ //does not work
System.out.println("Enter number:");
int num = input.nextInt();
divisibleBy3(Math.abs(num));
}
else if(option.equals("3")){ //works
System.out.println("Enter string:");
String sentence = input.nextLine();
System.out.println("Number of periods and spaces: " + periodsAndSpaces(sentence) + "\n");
}
else if(option.equals("4")){ //does not work
System.out.println("Enter the width of the triangle:");
int length = input.nextInt();
rightTriangle(length, "");
}
else if(option.equals("5")){ //exits the while loop
flag = false;
}
else{
System.out.println("That is not a valid option!");
}
}
对于上述if/else if语句,程序将执行给定的方法,然后显示菜单,后跟“That is not a valid input!”,然后再次打开菜单,即使用户没有输入任何内容
# 1 楼答案
我推断} 对象
input
变量是^{选项3是唯一一个按预期工作的选项,因为它是唯一一个使用
nextLine()
作为选项特定输入的选项,从输入缓冲区中清除输入末尾的换行符如果有人选择选项1,然后输入^{,则会发生以下情况:
input
包含字符串"3\n"
nextInt()
读3
input
中仍然有"\n"
尚未读取numOfColumns(3)
运行nextLine()
从input
读取,立即从第3步找到仍然存在的\n
,清除该字符,并返回一个空字符串option
的值""
将由无效的输入大小写决定nextLine()
等待新的输入内容再次可用要获得预期的行为,请在每次
input.nextInt()
调用后调用input.nextLine()
# 2 楼答案
如注释中所述,在使用
input.nextInt();
或任何其他不使用整行的方法后,需要使用该行的其余部分,因为它只接受部分行的输入,其余部分保留在扫描仪上。您可以通过input.nextLine();
来解决这个问题,使其超过当前行,以便在while循环重新启动时为下一个输入做好准备,如下所示:以下是使用上述技术的有效解决方案:
这使每个选项都能正常工作