Here's another JAVA Program I want to share with you guys, which is a demonstration of the Lottery class I was asked to design from my copy of Tony Gaddis' textbook.
Below is the code for the class:
import java.util.Random;
public class Lottery
{
private int[] lotteryNumbers;
private int matches;
public Lottery()
{
final int maxNumber = 10;
Random numberGenerator = new Random();
lotteryNumbers = new int[5];
for (int x = 0; x < lotteryNumbers.length; x++)
{
lotteryNumbers[x] = numberGenerator.nextInt(maxNumber);
}
}
public void lotteryCheck(int[] playersNumbers)
{
int numberOfMatches = 0;
for(int y : playersNumbers)
{
if (playersNumbers[y] == lotteryNumbers[y])
numberOfMatches++;
}
matches = numberOfMatches;
}
public int getNumberOfMatches()
{
return matches;
}
public int[] getLotteryNumbers()
{
return lotteryNumbers;
}
public void noWin()
{
System.out.println("Sorry, you did not win the grand prize.");
}
public void grandPrizeWinner()
{
System.out.println("Congratulations! All of your numbers match the lottery; you win the grand prize!");
}
}
Over here is the code that executes the class' methods:
import java.util.Scanner;
public class LotteryProgram
{
public static void main(String[] args)
{
boolean safeEntry = true;
final int arraySize = 5;
int[] playerNumbers = new int[arraySize];
int[] returnNumbers;
Scanner Keyboard = new Scanner(System.in);
System.out.println("This program will run a check for winners of a five-element lottery game. " +
"If all of your numbers matches the draw numbers, you win the big prize.");
System.out.println("\nFor each element, enter a number between 0 and 9 according to your paper.\n");
for (int x = 0; x < playerNumbers.length; x++)
{
System.out.println("Element " + (x + 1) + ":");
playerNumbers[x] = Keyboard.nextInt();
if (playerNumbers[x] < 0 || playerNumbers[x] > 9)
{
System.out.println("Invalid number. Please run the program again and enter a digit that is between 0 and 9.");
x = 5;
safeEntry = false;
}
}
if (safeEntry)
{
Lottery drawNumbers = new Lottery();
System.out.println("The numbers from the draw are as follows:");
returnNumbers = drawNumbers.getLotteryNumbers();
for (int p = 0; p < returnNumbers.length; p++)
{
System.out.print(returnNumbers[p]);
}
System.out.println();
if (drawNumbers.getNumberOfMatches() == 5)
drawNumbers.grandPrizeWinner();
else
drawNumbers.noWin();
}
}
}
Thanks for reading!
Friday 14 December 2012
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment