1

I came up with the following code to calculate the factorial of a given number:

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

}

}

if you execute the code, it reads a number from the keyboard and then prints out its factorial

I exported the code as a .jar file and tried to give the number (10) as input, from the terminal

I did as this post says How to execute jar with command line arguments but nothing happened until I typed again the number

-----------Terminal-----------

roditis@NiSLab-pc2:~/Desktop$ java -jar import_number.jar 10

enter a number:

10

execute Long-Running Task took 0ms.

the factorial of 10 is 3628800

-----------Terminal-----------

Im new to linux / programming and I really look forward for your help

Thanks in advance

Roditis

Community
  • 1
  • 1
Roditis
  • 13
  • 1
  • 3

1 Answers1

1

You should try putting the value in quotes like roditis@NiSLab-pc2:~/Desktop$ java -jar import_number.jar "10"

Remember that your main function takes an array of String objects like so public static void main(String[] args).

EDIT

Sorry, I see that you are not reading the args[] parameter at all. If you provide "10" as an argument to your program, then args[0] will contain that value. Please check if(args.length >= 1) in your case before accessing args.

Michiel
  • 270
  • 1
  • 3
  • 11
  • Michiel Thank you very much for your help :D From your EDIT i realized that i have to change the BigInteger number = new BigInteger (strPhone); into BigInteger number = new BigInteger (args[0]); and now it works like a charm :D – Roditis Jul 08 '12 at 13:16