Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Thursday, February 28, 2008

Sample Code On Factorial

Factorial.java
import java.util.*;
import java.lang.*;
public class Factorial {
public static void main(String[] args)
{
if (args.length == 0)
System.out.println("Example: java Factorial 10");
try
{
for (int i=0; i < args.length; i++)
{
System.out.print("Fact of Param # " + (i+1) + ": " + Fact(args[i]));
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
public static long Fact(String f) throws Exception
{
int f1 = Integer.parseInt(f);
long Result = 1;
if (f1 < 0)
throw new Exception("I can not calculate this!");
if (f1 > 20)
throw new Exception("that is a big ####");
try
{
for (int j=1; j <= f1; j++)
Result *= j;
}
catch(Exception e)
{
System.out.println(e.getMessage());
throw e;
}
return Result;
}
}

No comments:

Post a Comment