As part of a home work assignment I need to take a program that compares the time it takes to find the square root using newton's method and Math.sqrt, and implement a method that stops the program when a character is entered. As you can see, I created the method 'stop to do this, but I don't know how to put it into the main method. I tried to create an if statement that called the method when the character 's' was entered, but this caused the program to halt until a character was entered. My plan was to put the if statement within both for loops (which is what will be running for the majority of the time) and have the if statement be ignored if no characters were entered, but I'm not sure how to accomplish this. I'm not sure what to do at this point, so any help would be appreciated. Thanks :D
public class Compare
{
private final long start;
public Stopwatch()
{ start = System.currentTimeMillis(); }
public double elapsedTime()
{
long now = System.currentTimeMillis();
return (now - start) / 1000.0;
}
public void stop()
{
System.out.println("The Stopwatch program has been halted");
System.exit(0);
}
public static void main(String[] args)
{
double s = 0;
int N = Integer.parseInt(args[0]);
double totalMath = 0.0;
Stopwatch swMath = new Stopwatch();
for (int i = 0; i < N; i++)
{
totalMath += Math.sqrt(i);
}
double timeMath= swMath.elapsedTime();
double totalNewton = 0.0;
Stopwatch swNewton = new Stopwatch();
for (int i = 0; i < N; i++)
{
totalNewton += Newton.sqrt(i);
}
double timeNewton = swNewton.elapsedTime();
System.out.println(totalNewton/totalMath);
System.out.println(timeNewton/timeMath);
}
}