2012-07-08 68 views
1

我想出了下面的代碼計算給定數的階乘:如何使用終端參數執行jar文件?

import java.lang.*; 

import java.math.*; 

import java.io.*; 

import java.util.*; 

@SuppressWarnings("unused") 
class factorial_1{ 

public static void main(String args[]) throws IOException 

{ 

System.out.println("enter a number: "); 

String strPhone = ""; 
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

strPhone = br.readLine(); 

BigInteger number = new BigInteger (strPhone); 

BigInteger fact = new BigInteger("1"); 

BigInteger i = new BigInteger("1"); 

BigInteger step = new BigInteger("1"); 

final long start = System.currentTimeMillis(); 

final long durationInMilliseconds = System.currentTimeMillis()-start; 

for (; i.compareTo(number) <= 0; i=i.add(step)){ 

    fact = fact.multiply(i); 

} 

System.out.println("execute Long-Running Task took " + durationInMilliseconds + "ms."); 

System.out.println("the factorial of "+ number +" is "+ fact); 

} 

} 

,如果你執行的代碼,它從鍵盤讀取一個數字,然後 將打印出階乘

我導出的代碼作爲一個.jar文件,並試圖給輸入數(10),從終端

我照這個帖子中寫道:How to execute jar with command line arguments卻沒有任何反應,直到我再次輸入的號碼

----------- -----------航站樓

roditis @ NiSLab-PC2:〜/桌面$ Java的罐子import_number.jar 10

輸入一個數字:

執行長時間運行的任務拿了0毫秒。

10階乘是3628800

----------- -----------終端

林新的Linux /編程和我真的很期待您的幫助

在此先感謝

Roditis

回答

1

你應該嘗試把值在引號像[email protected]:~/Desktop$ java -jar import_number.jar "10"

請記住,您的主函數需要一個String對象數組,如public static void main(String[] args)

編輯

對不起,我看你是不是讀args[]參數都沒有。如果您提供"10"作爲您程序的參數,那麼args[0]將包含該值。在訪問args之前,請檢查您的案例中的if(args.length >= 1)

+0

媒體鏈接嘗試,但結果仍然是相同的:( – Roditis 2012-07-08 03:00:32

+0

米歇爾非常感謝您的幫助:d 從您的編輯我意識到,我必須改變 BigInteger的數量=新的BigInteger(strPhone); 分成 BigInteger number = new BigInteger(args [0]); 現在它的作用就像一個魅力:D – Roditis 2012-07-08 13:16:42