0

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

}
darclander
  • 1,526
  • 1
  • 13
  • 35
  • 2
    Presumably it should break when it's found the final answer. – jarmod Jun 18 '20 at 17:59
  • 1
    You might also want to look at https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Progman Jun 18 '20 at 18:00
  • The reason to why the `while`-loop will keep going forever is since you have nothing that tells it to go out of it. And in your first if-statement you are not changing the value of `x1` which means that the first `system.out.println` will never be reached. – darclander Jun 18 '20 at 18:00

3 Answers3

0

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.

Andrew
  • 1
  • 1
  • 1
    do you mean something like this? do{ x1 = (x1 +(a/x1))/2; } while (x1* x1 != a); System.out.println("Your final answer is" +" " + x1); (sorry for bad formatting) . Im basically trying to work out the sqaure root of a number using a method called newtons raphson to iterate over the last number to find the square root – CantCodeYet Jun 18 '20 at 18:30
  • Maybe this answer is better to have as a comment? – darclander Jun 18 '20 at 19:31
0

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/

0

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263