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