2012-07-08 45 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