2012-12-01 45 views
0

我想要做的是在這個已經存在的代碼上添加一個停止功能。我認爲我可以實現一個停止函數,如果我要把一個字符串輸入放到那裏,如果我輸入s來停止,那麼程序將在當前時間停止。所以,當我按s時,它的確如同運行時沒有if語句一樣在當前時間停止秒錶

public class Stopwatch { 

private final long t; 

public Stopwatch() 
{ 

    t=System.currentTimeMillis(); 

} 

public double elapsedTime() 
{ 

    return (System.currentTimeMillis() - t)/1000.0; 

} 

public double stopping(double newton, double time, double totnewt, double tottime) 
{ 
    double timeNewton = newton; 
    double timeMath = time; 
    double totalNewton = totnewt; 
    double totalMath = tottime; 

    StdOut.println(totalNewton/totalMath); 
    StdOut.println(timeNewton/timeMath); 


    return time; 
} 

public static void main(String[] args) 
{ 
    System.out.println("Enter N:"); 
    int N = StdIn.readInt(); 




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


    String s = StdIn.readString(); 
    if (s == "s") 
    { 

     swMath.stopping(timeNewton, timeMath, totalNewton, totalMath); 
     swNewton.stopping(timeNewton, timeMath, totalNewton, totalMath); 
    } 


    StdOut.println(totalNewton/totalMath); 
    StdOut.println(timeNewton/timeMath); 

} 
} 
+3

*「我認爲我可以實施......」*呃。那個計劃出了什麼問題? –

+0

我意識到它不會工作,因爲程序正在等待輸入。所以當我按下s時,它就像沒有if語句一樣運行。 – iii

+0

你確定你想要自己的秒錶?那裏有很多。考慮apache commons-lang –

回答

1

你的代碼中存在一個基本的java錯誤。

您無法將字符串與==運算符進行比較。

這僅適用於數字(如浮動,整型,雙等)

使用s.equals( 「S」),而不是在if條件

if (s.equals("s")) 
{ 
    swMath.stopping(timeNewton, timeMath, totalNewton, totalMath); 
    swNewton.stopping(timeNewton, timeMath, totalNewton, totalMath); 
} 

相當於是一個字符串函數比較字符串