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

问题描述 投票:0回答:2

即使while中的布尔值为false,循环仍然继续。我不知道怎么了。如果他们的答案没有被缓存,则应该将布尔循环变量设置为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;
    }

*编辑:在第11次浏览我的代码并完成更多代码后,结果发现问题出在顶部的另一个循环中,我没有正确解决问题,使其继续调用此循环,并且过度。我修复了它,现在可以了。非常感谢您,对此表示抱歉

java loops do-while
2个回答
3
投票

这就是我会做的-

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();
        }
    }
  }

0
投票

尝试这种方式:

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.