Java方法在验证输入时陷入无限循环

时间:2014-02-17 05:38:49

标签: java

不知怎的,我在这里玩得很开心,我只是不明白为什么。

这个方法应该确保输入是y或n,并且不是空白。 我应该注意这是针对学校的,需要2个单独的错误输出。

当我输入一个空行时,我在控制台上得到了一个空白行。 在那之后,或者在我特意输入错误数据(例如x)之后,下次我输入有效数据(如y或n)时,我会继续在无限循环中获取错误数据。

我做错了什么?

public static boolean getContinue(Scanner sc)
   {
   boolean decision = false;
   System.out.println("Continue? Y/N: ");
   String userChoice = sc.next();
   boolean isValid = false;
   while (isValid == false)
   {
       if (userChoice.equalsIgnoreCase("y"))
       {
           decision = true;
           isValid = true;
       }
       else if (userChoice.equalsIgnoreCase("n"))
       {
           decision = false;
           isValid = true;
       }
       else if (userChoice.equals(""))
       {
       System.out.println("Error! This entry is required. Try again.");
       userChoice = sc.next();
       }
       else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
       {
        System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
        userChoice = sc.next();
       }
   }
   return decision;
   }

注意: 修订了守则以包括

新的控制台输出(仍然错误)

格式化结果 贷款金额:5.00美元 年利率:500% 年数:5 每月付款:2.08美元

继续?是/否:

b 错误!输入必须是'Y'或'N'。再试一次。 ÿ 错误!输入必须是'Y'或'N'。再试一次。 ÿ 输入贷款金额:

4 个答案:

答案 0 :(得分:2)

您没有将变量userChoice设置为新值。将您的最后一个if子句更改为

System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();

答案 1 :(得分:0)

因为userChoice永远不会在循环内部发生变化(这是因为你没有改变它)。

答案 2 :(得分:0)

如果是部分,请查看其他内容:

else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))

这里你做了2个错误:

  • 您使用的是|bitwise运营商,而不是logical
  • 逻辑需要logical AND&&)来获取输入不是yn
  • 的情况

正确的else-if

else if (!userChoice.equalsIgnoreCase("y") && (!userChoice.equalsIgnoreCase("n")))
{
    System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
    userChoice = sc.next();
}

答案 3 :(得分:0)

您必须使用sc.nextLine()才能抓住Empty Blank Line。因此,将所有sc.next()的实例替换为sc.nextLine()

相关问题