black sleep
black sleep

Reputation: 13

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

Upvotes: 0

Views: 1130

Answers (2)

ant_dev
ant_dev

Reputation: 769

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

Upvotes: 0

JoeChris
JoeChris

Reputation: 231

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

Upvotes: 3

Related Questions