Wednesday, November 11, 2009

Core Java Programs

/** Welcome
* This program displays a greeting from the authors.
* @version 1.20 2004-02-28
* @author Cay Horstmann
*/
public class Welcome
{
public static void main(String[] args)
{
int[] greeting = new int[3];
greeting[0] = 3;
greeting[1] = 5;
greeting[2] = 5;

for (int g : greeting)
System.out.println(g);
}
}
_______________________________________________________

import java.math.*;
import java.util.*;

/** Big Integer Test
* This program uses big numbers to compute the odds of winning the grand prize in a lottery.
* @version 1.20 2004-02-10
* @author Cay Horstmann
*/
public class BigIntegerTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();

System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();

/*
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/

BigInteger lotteryOdds = BigInteger.valueOf(1);

for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(
BigInteger.valueOf(i));

System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
}
}
_____________________________________________________________________________________

No comments: