2017-04-09 89 views
-4
public class RandomPrint { 
    public static void randomprint(){ 
     for (int i=0;i<100000000;i++){ 
      System.out.println((int)(1+Math.random()*10)); 
     } 
    } 
    public static void main(String[] args){ 
     long begain = System.currentTimeMillis(); 

     long CheckTime = System.currentTimeMillis(); 
     while(true){ 
      RandomPrint.randomprint(); //this is the program need to work 
      CheckTime = System.currentTimeMillis(); 
      if((CheckTime-begain)>=(10*1000)){ 
       System.out.println("10 seconds stop!"); 
       break; 
      } 
     } 
    }  
} 

這是我的java代碼,程序是「randomprint()」,但10秒後,程序不停止!(程序將始終工作)。你可以幫我在10秒鐘後讓程序停止工作嗎?謝謝!如何讓程序工作10秒?並在10秒後程序將停止

+0

當您調試,會發生什麼?你期望他們的價值是什麼?代碼的行爲在哪裏與預期的行爲有所不同? – David

+0

這就是調試器存在的原因。 – OldProgrammer

+0

您的程序似乎按照預期的願望工作(運行10秒鐘然後停止)。什麼不對? – VHS

回答

0

在方法randomprint中完全刪除for-loop,但保留它的單行體,它將按預期工作。

+0

謝謝!我做到了! –

0

那麼我對你的代碼做了一些修改,因爲for循環我們必須打破它,所以我們會在你想要的時間內打破它,現在這次我會把時間傳遞給你的方法,看看

public static void randomprint(int seconds){ 
    long start = System.currentTimeMillis(); 
    long end = start + (seconds)*1000; // seconds * 1000 ms/sec 
     for (int i = 0;i<100000000;){ 
     System.out.println((int)(1+Math.random()*10)); 
     i++; 
     if(System.currentTimeMillis() >= end) break; 


    } 
} 

public static void main(String[] args) { 

     //Stop my program at 3 seconds 
     randomprint(3); 

} 

更改爲10 3號,有你有;)

+0

謝謝!我做到了! –

+0

如果它工作,你能給我一些觀點嗎? ty – Yussef

+0

好的,沒問題,但是我不知道怎麼給你點,你能告訴我一步嗎?謝謝! –