简体   繁体   中英

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. 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.

    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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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