## Project Two: Simple Lotto – Process

Overview

The Simple Lotto game uses custom methods to run the code rather than just the main method.  This program could have been broken down futher into different classes and using more methods, but after the trials I faced with this program I decided to keep it simple for now.  Simple Lotto also utilizes ArrayList objects instead of a typical array to hold the player’s numbers, computer’s numbers, and matching numbers.  There are some different conditional statements checking for duplications, input, and case size.

Process

I began by declaring three ArrayLists of Integers that would each be used to hold a set of numbers.  One would hold the player’s input, a second to hold the computer’s randomly generated numbers, and a third to hold the numbers that were matching numbers.

I decided to just put everything inside of a method so I had to create an object of SimpleLotto to use the method to run the program.

Inside of the method the program displays a welcome message and asks the user for input.  To fill the pNums ArrayList with the user’s input I had to use a for loop.  This could have been done two ways, by using a final as a conditional inside the loop or by using the size() method of the ArrayList object.  I decided to use some final variables since I already know the program would need 10 player numbers, 20 computer numbers, 0 for a minimum value and 80 for a maximum value.

Inside of the loop, the program uses a Scanner object to get the next input from the user.  It then checks to make sure the input was greater than or equal to zero and less than or equal to eighty.  If the conditions were not met, it outputs a message to the user displaying the value of the input and requesting a new number, then decrements the variable used to hold the number of iterations of the loop.  If the conditions were met, the program moves on to another conditional statement to check if the user had already input the number entered.  If the input passed both conditional tests (between zero and eighty and is a new number) the input was added to the ArrayList using the add() method.

Outside of the first for loop the program displays the input to the user and asks if they wish to continue on.  Another conditional statement was added here to check if the user enters anything other than a “P” or a “Q” providing them with a message to enter their decision again.

Based on the users input the program branches off from here. If the player enters “Q” or “q”, the program calls the quit() method and displays a goodbye message to the user.  If the user enters a “P” or “p” the program continues to generate random numbers.

**NOTE** This part had me stuck for a while.  I had used a nested for loop with the initial program that used basic arrays but in the process of recreating that nested for loop I got stuck.  I was able to generate twenty random numbers between 0 and 80 without a problem but when I tried to have the program check if that number had already been generated, I got stuck.  I ended up creating a thread over at the JavaRanch and to have the members of the forum take a look at the portion of the code.  They were helpful as always and pointed out what I was doing wrong and why it was acting the way it was (creating the duplicate number anyways).

To generate twenty different random numbers I used a while loop.  The condition of the while loop was the size of the ArrayList and if it was under the value of the final CNUMS variable.  While inside of the loop, the  program creates a new random number and assigns it to a new Integer variable num.  A second conditional statement was used to check the contents of the array for the number.  If the cNums ArrayList did not have an element equal to the new num variable then that value held by num was added to the cNums ArrayList.

Outside of the while loop the program continues by displaying the contents of cNums to the user.  After displaying the contents of the cNums ArrayList, I used a third loop to fill the last ArrayList with matching numbers.  This loop cycled through the larger ArrayList, cNums, and compared each element with the pNums ArrayList.  If the objects inside of each element were equal, that element was added to mNums.

Finally the program displays the matching numbers and the number of matches using the ArrayList’s size() method.

Final Thoughts

Simple Lotto didn’t end up being so simple.  I began by creating a GUI using Swing and providing the user with a board containing 80 grids showing a number on each grid.  The bottom of the screen provided the user with an area to enter their name and their numbers.  The right portion of the screen was the Score Board, which was supposed to contain the user’s name, user’s numbers, computer generated numbers, matching numbers, and a score based on the number of matches.  I threw in some standard text output to display using println and everything was working fine (printing out the correct information), but the ScoreBoard would not refresh itself showing the updated information.  After doing some research and fussing around with valide() and repaint() I believe the issue is with Threads, or my lack of multithreading knowledge at this point (which is almost nonexistant).

I decided to start over again removing the Swing components and making it a simple console based program using standard arrays.  I was able to get the project to work as intended by checking conditionals and providing accurate output. I wasn’t entirely happy with the difficulty increase from project one to project two so I decided to change it up a little bit.  I recalled reading about ArrayLists and I was interested in learning more about them.  This projected ended up being a perfect place to start learning about them and using them.

This project ended up being exactly what I was looking for, which is a good learning experience.  Encountering the troubles with the GUI, I learned a bit about Threads, touched up on exception handling, and got more experience with Swing and AWT.  The decision to recreate the program using ArrayLists was even more beneficial.  I have learned to use ArrayList objects and its methods and know have an understanding of wrapper classes as well.

## Project Two (Simple Lotto Game) Source Code

```import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class SimpleLotto {

//declare instance variables
Random rGen;// = new Random();	//Random object to generate random numbers
ArrayList pNums;	//Holds numbers input from player
ArrayList cNums;	//Holds randomly generated numbers
ArrayList mNums;	//Holds matched numbers

public static void main (String [] args)
{
SimpleLotto lotto = new SimpleLotto();
lotto.go();
}//end main method

//run method
public void go()
{
//Send text output to user
System.out.println("Welcome to Simple Lotto! \n");
System.out.println("Enter " + PNUMS + " numbers between " + MIN_VALUE +
" " + MAX_VALUE + ".");

//Initialize array to hold user input
pNums = new ArrayList();

//Create Scanner object to get input from user
Scanner scanner = new Scanner(System.in);

for(int i = 0; i < PNUMS; i++)
{
int number;	//variable to hold input for conditional
number = scanner.nextInt();

//check if number is not between MIN and MAX values
if(number < MIN_VALUE || number > MAX_VALUE)
{
//Show input to user
System.out.println("You entered " + number + ".");
//Request another number
System.out.println("Please enter a number between " + MIN_VALUE +
" " + MAX_VALUE + ".");

//decrement i for another iteration of the loop
i--;
}//end if ( < 0 || > 80)
else
{
//check if duplicate entry
if(pNums.contains(number))
{
System.out.println("You entered " + number + " more than once.  Please choose another number.");
number = scanner.nextInt();
//decrement i for another iteration of the loop
i--;
}
else
{
}//end else
}//end else
}//end for loop

//Show numbers to user
System.out.println("\nYou entered: " + pNums.get(0) + ", " + pNums.get(1)+ ", " + pNums.get(2) + ", "
+ pNums.get(3) + ", " + pNums.get(4) + ", " + pNums.get(5) + ", " + pNums.get(6) + ", "
+ pNums.get(7) + ", " + pNums.get(8) + ", " + pNums.get(9) + ".");
//Request input to continue
System.out.println("************************");
System.out.println("Press \"P\" to play.");
System.out.println("Press \"Q\" to quit.");

//create variable to hold next input then get input from user
String in = scanner.next();

//Checks to see if entry is a "P" or a "Q"
while(!(in.equalsIgnoreCase("P") || in.equalsIgnoreCase("Q")))
{
System.out.println("Please enter a P or a Q.");
in = scanner.next();
}
//if "P"lay
if(in.equalsIgnoreCase("P"))
{
//initialize ArrayList to hold computer generated numbers
cNums = new ArrayList();
//initialize ArrayList to hold matching numbers
mNums = new ArrayList();
//instantiate rGen
rGen = new Random();

//fill the array with random numbers
while(cNums.size()			{
Integer num = (Integer)rGen.nextInt(MAX_VALUE);
if(!cNums.contains(num));
}//end while loop generating random numbers

//Show generated numbers to user
for(int i = 0; i < CNUMS; i++)
{
System.out.println("Number " + (i + 1) + ":\t" + cNums.get(i));
}

//loop to fill mNums with matches
for(int l = 0; l < cNums.size(); l++)
{
if(pNums.contains(cNums.get(l)))
{
}
}

/*
* Output number of matches
*/

int matches = 0;	//counter for mNums

System.out.println("************************");
System.out.println("\nMatching Numbers:  ");

//for every element of mNums
for(int i = 0; i < mNums.size(); i ++)
{
System.out.print(mNums.get(i) + "\t");
matches++;
}

System.out.println("\nYou matched " + mNums.size() + " numbers.\nThanks for playing!");
}//end if "P"

//if user enters "q" or "Q"
if(in.equalsIgnoreCase("Q"))
{
quit();
}//end if "Q"
}//end go method

//method sends message when user enters "Q"
public void quit()
{
System.out.println("Good Bye.");
}//end quit method

final int MAX_VALUE = 80;	//Highest number allowed
final int MIN_VALUE = 0;	//Lowest number allowed
final int PNUMS = 10;	//Amount of numbers from user
final int CNUMS = 20;	//Amount of numbers to generate

}//end SimpleLotto class
```

## Project Two: Lottery Game

Project Two:

• Project One Skills
• ArrayLists
• More Conditionals

Simple Lotto Game

The player will be requested to enter a series of numbers.  The computer will randomly generate a set of numbers then will show them to the user.  After the final number has been generated, the computer will provide the player with how many numbers match.

See The Code

Simple Lotto source code

Play Game

I’ll provide a link here after I cover Applets or possibly WebStart.

## Breaking Project 1

Even in a project as simple as this one, it wasn’t hard to find where I could “break” the existing code and cause the program to throw an exception.

• What if the user entered a number less than 1 or greater than 100?
• What if the user entered a number larger than the value that can be held inside of the int variarble userNum?
• What if the user entered a letter, that couldn’t be converted to an int, instead of a number?

At this point in time I can only check with a conditional statement because I haven’t covered how to catch/throw exceptions. The best I can do is insert a conditonal into the loop to test if the number is larger than or equal to one or less than or equal to 100.

```if(userNum < 1 || userNum > 100)
{
System.out.println("You'll never guess it that way!  Pick a number between 1 and 100. \n");
userNum = input.nextInt();
}
```

If the user enters input that can not be converted to an int, the program will still terminate with an exception.

## Project One: Process

Overview

The guessing game was a very easy project and I think a good place to start getting back to the basics. I admit I did have to consult the API for generating a random number because that isn’t something that was covered in class. Also at this point in time, packaging the files and publishing them online (Applets) is a bit over my head.

Because this was a beginning project I didn’t worry about encapsulation and just threw all my code inside of one class and let main do all the work.

Process

1. I began by declaring the variables that I though would be required by the project. These would include a number that will be set by the computer (ranNum), a number that the user will be guessing (userNum), a number to hold the amount of guesses by the user (numGuesses), a Scanner object to get the input from the user at the command line (input), and some Strings to hold the appropriate messages to display.
2. *NOTE* I never used to place messages inside of a String and would initially just use println to display what I wanted when I needed it. After taking the C++ class and messing around with pointers, I got into the habbit of setting Strings to hold complete messages and it’s something that stuck with me. Whether this is something that developers use in a professional setting, I’m not sure.

**NOTE** I need to get acquanted with the printf method of formatting text. Using println was something that was encouraged by the instructor because “you can do the same thing with println as you can with printf with just a little more code.”

3. I created the message to display to the user when they first run the program (notice I forgot to use a String holding that message this time).
4. The program had to ask for a number at least once so I threw it into a do/while loop.

Inside the Loop:

1. I first initialized the objects and variables to be used inside of the loop. input was to be used to set userNum to whatever the user entered next.
2. The String variables had to contain an actual message so initialized them here.
3. numGuesses was incremented to 1 and continues to increment for each iteration of the loop.
4. I set up a series of nested if/else conditionals. This could have been done differently and I probably would have set up three different if statements and one else statement, but I wanted to incorporate some nesting into the program for practice.
5. Finally the while portion of the do/while checks if the user guessed correctly.

Filling In The Blanks

The random number generator is new to me.  I had remembered reading about the Math class and its random() method but I did not know how it actually worked.  My first version of the code included the following line of code:  ranNum = math.random();  where I assumed the constructor would take a numerical value that would be the high end of the random number generated.  However, the random() method only returns a random double value between 0.0 and 1.0 not an int like I had thought.

After doing some more searching through the APIs and consulting the web for more information I came across the Random class.  From here I was able to get the nextInt() method and threw my 100 into the constructor.

I will need to become more familiar with the Random class and the Math class as I progress.  There seems to be a good deal of information regarding several methods and how to seed those “random” values.

## Project 1: Source Code

```/*
* GuessGame
*/

import java.util.Random;
import java.util.Scanner;

/*
* Jason Sgalla
* April 6, 2011
*/

public class GuessGame {

public static void main (String [] args)
{
int numGuesses;	//number of guesses made by user
Random rGen;	//random number generator
int ranNum;	//random number generated
int userNum;	//guess chosen by user
String yMesg;	//message to display when userNum == ranNum
String hMesg;	//message to display when userNum > ranNum
String lMesg;	//message to display when userNum < ranNum
Scanner input;	//scanner object to get user input

//initialize random generator and get random number
rGen = new Random();
ranNum = rGen.nextInt(100);
numGuesses = 0;

//Send output to user
System.out.println("I'm thinking of a number between 1 and 100." +
"\nCan you guess the number?");
do
{
//initialize scanner object
input = new Scanner(System.in);

userNum = input.nextInt();

//initialize String variables
yMesg = "You guessed it!";
hMesg = "Too high.  Try again.";
lMesg = "Too low.  Try again.";

//increase the number of guesses
numGuesses++;

//if user's guess is correct
if(userNum == ranNum)
{
System.out.println(yMesg);
System.out.println("It took you " + numGuesses +
" guesses.");

}
else
//if user's guess is too high
if(userNum > ranNum)
{
System.out.println(hMesg);
}
else
//if user's guess is too low
if(userNum <; ranNum)
{
System.out.println(lMesg);
}
//continue with loop until user chooses correct answer
}while(ranNum != userNum);
}//end main method
}//end GuessGame class
```

## Introduction (Hello Blog)

I have created this blog for the purposes of keeping a record of my journey through Java and the applications created while I travel along that path.

I began learning Java back in 2010 when I was required to take a Java class for my Associate program.  I completed the class with an “A” and continued focusing on the remainder of the classes required for my program.   I soon discovered that a lot of the information I had learned in class had left me because I neglected to continue using the language.

Here I am, one year later, and I have decided to start over from the beginning once again.  However, this time around I will be creating applications to help retain the information learned and will be better prepared for the Java II class coming up in the Bachelor program.

I will be providing all source code on the site for anyone to reveiw and comment on.  The objective is to obtain constructive feedback about my programming practices and recommendations based on practices employed by those who have used the language in a professional environment.  Any suggestions are appreciated  and can only benefit me in the long run, so feel free to leave comments on the code.

Thanks

Jason Sgalla