1

I need to create a program that uses while to find the volume of a cylinder. I need the while loop to break if the user inputs a negative value for the height. My code looks like this:

double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
    final double PI=3.14159;
    boolean NotNegative=true;

while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
        System.out.print("Enter height (Use negative to exit): "); // has the user input the height
        h=Double.parseDouble(br.readLine());
        sentinel=h; // save sentinel as the inputted height

        while(sentinel>0){

           System.out.print("Enter radius: "); // have the user input the radius
           r=Double.parseDouble(br.readLine());
           v=PI*(r*r)*h; // find the volume
           System.out.println("The volume is " + v); // print out the volume
           count++; // increase the count each time this runs
           NotNegative=true;
           sentinel=-1;
        }
    }   

Any help?

2
  • 3
    And why don't you want break or if ? Commented Dec 3, 2012 at 17:00
  • 5
    Is Math.PI too accurate? ;) Commented Dec 3, 2012 at 17:03

2 Answers 2

2

You can throw an Exception which you catch and ignore. This is bad idea as

  • if and/or break is more efficient and simpler.
  • it's slow
  • it's confusing.

However, since you are using a while loop, which is like using an if & break, you can do the following.

NotNegative = h >= 0;
Sign up to request clarification or add additional context in comments.

Comments

0

Add the following code inside the while(NotNegative){, after reading the input.

NotNegative = h >= 0;

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.