如何在不中断和退出整个循环的情况下跳过一个提示并继续下一个提示?JAVA
因此,我正在开发一个程序,允许用户将学生添加到班级中,并管理他们的成绩等等。当用户选择菜单中的第一个选项时,他必须输入一个id(必填),但他也可以添加数字分数和/或字母等级。根据另一篇文章中的反馈,我设法创建了一个字符串变量行来读取用户输入,然后检查它是否为“S”/“S”(跳过或不跳过),并相应地将值解析为double。现在,基于这个问题,如果用户决定跳过添加分数,我如何跳过提示并继续下一个提示?我尝试使用break;但它退出了整个循环。有没有办法跳过分数问题,继续字母分数问题 输出: 1) 将学生添加到班级如何在不中断和退出整个循环的情况下跳过一个提示并继续下一个提示?JAVA,java,skip,Java,Skip,因此,我正在开发一个程序,允许用户将学生添加到班级中,并管理他们的成绩等等。当用户选择菜单中的第一个选项时,他必须输入一个id(必填),但他也可以添加数字分数和/或字母等级。根据另一篇文章中的反馈,我设法创建了一个字符串变量行来读取用户输入,然后检查它是否为“S”/“S”(跳过或不跳过),并相应地将值解析为double。现在,基于这个问题,如果用户决定跳过添加分数,我如何跳过提示并继续下一个提示?我尝试使用break;但它退出了整个循环。有没有办法跳过分数问题,继续字母分数问题 输出: 1) 将
2) 开除学生 3) 为学生设置分数
4) 编辑学生的成绩
5) 显示课堂报告
6) 出口 一, 请输入id: 请输入分数:(输入s跳过) 请输入成绩:(输入s跳过) 代码
// Prompting the user for Score (Numerical Grade)
System.out.println("Kindly input Score: (Enter s to Skip)");
// reading the input into the line variable of string datatype
String line = input.nextLine();
// checking if line =="s" or =="S" to skip, otherwise
// the value is parsed into a double
if("s".equals(line) || "S".equals(line))
{
break; // this exists the loop. How can I just skip this requirement
//and go to the next prompt?
}else try
{
score = Double.parseDouble(line);
System.out.println(score);
} catch( NumberFormatException nfe)
{
}
// Prompting the user for Numerical Grade
System.out.println("Kindly input Grade: (Enter s to Skip)");
String line2 = input.nextLine();
if("s".equals(line2) || "S".equals(line2))
{
break; // this exists the loop. How can I just skip this
// requirement and go to the next prompt?
}else try
{
score = Double.parseDouble(line2);
System.out.println(score);
} catch( NumberFormatException nfe)
{
}
只需删除
中断
:
if("s".equals(line) || "S".equals(line))
{
// Don't need anything here.
}else {
try
{
score = Double.parseDouble(line);
System.out.println(score);
} catch( NumberFormatException nfe)
{
}
}
但最好不要有一个空的true
案例(或者,它是不必要的):
您还可以使用
String.equalsIgnoreCase
来避免需要测试“s”
和“s”
使用继续
关键字break
将退出整个循环,而continue
只是跳过下一步。这是不正确的continue
跳过循环体的其余部分,而OP希望转到下一个提示符,该提示符也在循环体中。我的坏消息。在这种情况下,听起来他最好只做if(!“s”.equalsIgnoreCase(line)){//try statement here}
Demorgan定律在起作用:)
if (!"s".equals(line) && !"S".equals(line)) {
try {
// ...
} catch (NumberFormatException nfe) {}
}