I'm having an issue with a method that is trying to find the square root of the number. The previousG is a randomly generated number. The number is the square roots actual number. I'm getting a stack overflow error. I realize why since I'm not updating the nextGuess variable. I'm wondering what I should add to the FindTheRoot method to stop this. Furthermore, I'm doing this recursively.
public static void main(String[] args) {
int srootArray[] = {9, 17, 25, 37, 49, 55, 999};
Random randomGuess = new Random();
for (int index = 0; index < srootArray.length; index++)
{
int previousGuess = randomGuess.nextInt(srootArray[index] + 1);
System.out.println("Number: " + srootArray[index] + "... " +
"First Guess: " + previousGuess);
FindTheRoot(previousGuess, srootArray[index]);
System.out.println("--------------------------------------------
------");
}
}
public static double FindTheRoot(double previousG, int number)
{
double errorMargin = 0.00001;
double nextGuess = (previousG + number / previousG) / 2;
if (nextGuess < errorMargin)
return nextGuess;
else
{
System.out.printf("%S%.4f%n", "Next Guess: " , nextGuess);
FindTheRoot(nextGuess, number);
}
return nextGuess;
}
}