简体   繁体   中英

Having issues with loops

Im having problems with a loop I made. It gets the right answers but it keeps on looping. I know it's because of the while(true) section, but I cant see where a break (if needed) should be. Is there a better way to write this? Also why does it only work when I add the second System.out.println? I was hoping it would loop till the condition was met

Thanks

import java.util.Scanner;

public class babyalgo
{

    private float a ; //the Number that the user is finding the sqrt of
    private float x1 = 2 ; // the starting guess 
    private double x2;
    /**
     * Constructor for objects of class babyalgo
     */
    public  void main (String[] args)
    {
        // initialise instance variables

        Scanner scan = new Scanner(System.in); // creating a scanner to take the user input
        System.out.println("Please enter your the number you wish to square root");
        float a = scan.nextInt();

        while (true){
            if (x1* x1 == a){
               System.out.println("Your final answer is" +" " +  x1);
            }

            else {
                x1 = (x1 +(a/x1))/2;
                System.out.println("Your final answer is" +" " +  x1);                 
            }
        }
    }

}

Why not use a do while loop so it executes at least once and then evaluate a condition for it to exit? Maybe I need a better explanation of what you're trying accomplish.

First of all you have no break statement in you loop.
Also you have wrong comparison statement x1 * x1 == a.
You can read more by the link https://howtodoinjava.com/java/basics/correctly-compare-float-double/

You should loop while the condition is not true , so while(... .=...) . Then within the while loop you can implement the change of x1 and after the while loop you can print out the result.

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