作爲家庭作業的一部分,我需要一個程序比較使用牛頓方法和Math.sqrt找到平方根所需的時間,並實現停止方法輸入字符時的程序。正如你所看到的,我創建了方法'stop 來做到這一點,但我不知道如何把它放入主要方法。我試圖創建一個if語句,在輸入字符'時'調用該方法,但這導致程序停止,直到輸入字符。我的計劃是將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);
}
}
還挺看起來像一個難題:http://stackoverflow.com/questions/1 0154153/Java的是,有-A-方式觀看的-IF-A-關鍵是,壓不阻斷 – Blorgbeard