简体   繁体   English

Java do while 循环在条件为假时不会停止

[英]Java do while loop doesn‘t stop when condition is false

The loop still goes on even when the boolean in the while is false.即使 while 中的 boolean 为假,循环仍然继续。 I'm not sure what's wrong.我不确定出了什么问题。 The boolean loop variable is supposed to be set to false if they answer isn't cached releasing you from the loop but for some reason, the program isn't doing that. boolean 循环变量应该设置为 false 如果他们的答案没有被缓存将您从循环中释放,但由于某种原因,程序没有这样做。

    public static double getvalue(String unit) {
        double answer = 0;
        boolean loop = true;
        do {
            try {
                System.out.println("enter the " + unit);
                answer = sc.nextDouble();
                loop = false;
            } catch (Exception e) {
                System.out.println("has to be a double");
                sc.nextLine();
            }
        } while (loop);
        return answer;
    }

*Edit: After looking through my code for the 11th time and after finishing more of it, it turns out the problem was in a different loop at the top which I didn't resolve correctly making it to keep calling this loop over and over. *编辑:在第 11 次查看我的代码并完成更多代码后,事实证明问题出在顶部的另一个循环中,我没有正确解决它,使其不断地一遍又一遍地调用这个循环。 I fixed it and now it works.我修复了它,现在它可以工作了。 Thanks you so much and sorry about that非常感谢你,对此感到抱歉

This is what I would do--这就是我要做的——

public static double getValue(String unit) {
    Scanner keys = new Scanner(System.in);
    double answer = 0;

    System.out.println("Enter a double: ");
    while (true) {
        try {
            answer = keys.nextDouble();
            return answer;
        } catch (Exception exc) {
            System.out.println("number has to be a double!");
            keys.nextLine();
        }
    }
  }

Try this way:试试这个方法:

public static double getvalue(String unit) {
double answer = 0;
boolean loop = true;
do {  
try {
         System.out.println("enter the " + unit);
         answer = (double) sc.nextDouble();
         break;
    } catch (Exception e) {
        System.out.println("has to be a double");
        sc.nextLine(); 
        }
   } while (true);
   return answer;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM