【问题标题】:How to skip a prompt and proceed to the next without breaking and exiting the entire loop? Java如何在不中断和退出整个循环的情况下跳过提示并继续下一个?爪哇
【发布时间】:2016-05-24 23:22:59
【问题描述】:

所以我正在开发一个程序,允许用户将学生添加到班级以及管理他们的成绩等等。当用户选择菜单中的第一个选项时,他必须输入一个 id(强制),但他也可以添加一个数字分数和/或字母等级。根据另一篇文章中的反馈,我设法创建了一个读取用户输入的字符串变量行,然后检查它是否是“S”/“s”(是否跳过)并相应地将值解析为 double。现在基于这个问题,如果用户决定跳过添加分数,我如何跳过提示并继续下一个提示?我尝试使用 break;但它会退出整个循环。有没有办法跳过分数问题并继续进行字母等级问题?

输出:

1) 将学生添加到班级
2)从班级中删除学生 3) 为学生设置成绩
4) 编辑学生的成绩
5) 显示课堂报告
6) 退出

1

请输入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)
{

}

【问题讨论】:

    标签: java skip


    【解决方案1】:

    只需删除break

    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 案例(或者,更确切地说,它是不必要的):

    if (!"s".equals(line) && !"S".equals(line)) {
      try {
        // ...
      } catch (NumberFormatException nfe) {}
    }
    

    您也可以使用String.equalsIgnoreCase 来避免需要测试"s""S"

    【讨论】:

    • 德摩根定律在行动 :)
    【解决方案2】:

    使用continue 关键字。 break 将退出整个循环,而 continue 只是跳过下一件事。

    【讨论】:

    • 这是不正确的。 continue 跳过循环体的其余部分,而 OP 想要转到下一个提示,它也在循环体中。
    • 我的错。在这种情况下,听起来他最好只做if (!"s".equalsIgnoreCase(line)) { //try statement here }
    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多