2013-07-15 26 views
0

作爲家庭作業的一部分,我需要一個程序比較使用牛頓方法和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); 

    } 
} 
+0

還挺看起來像一個難題:http://stackoverflow.com/questions/1 0154153/Java的是,有-A-方式觀看的-IF-A-關鍵是,壓不阻斷 – Blorgbeard

回答

0

我建議你閱讀關於Java線程..

你不能完成你正在嘗試沒有這個做。祝你好運!

0

主要方法是靜態方法。您只能在其中調用靜態方法,或者創建可以執行操作的對象。從我的角度來看,你有兩個選擇:

  1. 創建比較類的一個對象,並調用方法(裏面的main())

    Compare obj = new Compare(); 
    obj.stop(); 
    
  2. 使得停車()方法靜態的(從類調用它本身,而不是從一個對象):

    public class Compare { 
        public static void stop() { 
         System.out.println("The Stopwatch program has been halted"); 
         System.exit(0); 
        } 
    } 
    
    public static void main(String[] args) { 
    // Processing here... 
    
    // Here you want to stop the program 
    Compare.stop(); 
    } 
    
相關問題