创建一个rechecking if语句

时间:2016-04-14 20:35:14

标签: java

我正在为我的班级做一个平均成绩的脚本,我无法弄清楚如何让我的交叉检查部分重复,直到我有一个有效的值(代码如下所示)。当运行时,它允许我在原始输入无效的情况下进行校正,但仅执行一次。我怎样才能循环直到得到正确的答案?提前谢谢!

  if (grade1 >= 0 && grade1 <= 100)
     System.out.println("First grade valid.\n");
  else
     {
        System.out.println("Grade invalid.  Re-enter first grade:");
        grade1 = kb.nextDouble();
     }

4 个答案:

答案 0 :(得分:1)

考虑

grade = -1;
System.out.println("Enter a grade:\n");
grade1 = kb.nextDouble();
if (grade1 >= 0 && grade1 <= 100)
{
    System.out.println("First grade valid.\n");
}
else
{
    while (grade1 < 0 || grade1 > 100)
    {
        System.out.println("Grade invalid.  Re-enter first grade:");
        grade1 = kb.nextDouble();
    }
}

答案 1 :(得分:0)

试试这个:

while ((grade = Integer.parseInt(JOptionPane.showInputDialog("Enter a grade"))) < 0 || grade > 100) {
    System.out.println("Invalid grade of: " + grade);
}

但它并没有很好地处理字母,如果你输入“a”它会抱怨并对你大喊

答案 2 :(得分:0)

Chara,作为最初执行的方法,我进行了设置,以便用户插入输入并在输入后交叉检查有效性(参见下面的第一段摘录)。如果我可以在初始输入时主动交叉检查,最好保存空间(参见下面的第二部分摘录)。 Lew Bloch,我理解你所得到的,这对我来说是一个轻微的疏忽。从现在开始,我的回答会更好。

//交叉检查

  if (grade1 >= 0 && grade1 <= 100)
     System.out.println("First grade valid.\n");
  else
     {
        System.out.println("Grade invalid.  Re-enter first grade:");
        grade1 = kb.nextDouble();
     }

//成绩录入

  grade1 = kb.nextDouble();
  while (grade1 < 0 || grade1 > 100)
  {
     System.out.println("Entered grade is invalid.  Re-enter grade:");
     grade1 = kb.nextDouble();
  }

答案 3 :(得分:0)

try (Scanner scanner = new Scanner(System.in)) {
    System.out.println("Enter a grade:\n");
    double grade1 = scanner.nextDouble();
    if (grade1 >= 0 && grade1 <= 100)
    {
        System.out.println("First grade valid.\n");
    }
    else
    {
        while (grade1 < 0 || grade1 > 100)
        {
            System.out.println("Grade invalid.  Re-enter first grade:");
            grade1 = scanner.nextDouble();
        }
    }
}