0

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

3
  • 2
    looks OK to me, can you make a small complete program that shows the problem? Commented Apr 8, 2020 at 20:18
  • 1
    When I run this code, the while loop ends when I enter a numeric value (double), otherwise the while loop remains. but whats the problem? Commented Apr 8, 2020 at 20:19
  • use while loop instead of do-while Commented Apr 8, 2020 at 20:27

2 Answers 2

3

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();
        }
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.