作为家庭作业的一部分,我需要一个程序来比较使用牛顿法和 Math.sqrt 求平方根所需的时间,并实现一个在输入字符时停止程序的方法。如您所见,我创建了方法'stop 来执行此操作,但我不知道如何将其放入 main 方法中。我试图创建一个 if 语句,在输入字符“s”时调用该方法,但这会导致程序停止,直到输入一个字符。我的计划是将 if 语句放在两个 for 循环中(大多数情况下都会运行),如果没有输入任何字符,则忽略 if 语句,但我不确定如何实现这一点。我不确定此时该怎么做,所以任何帮助将不胜感激。感谢: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);
}
}