Java Practice Assignment #1

by Trevor Page on December 20, 2012

Right Click Here to Download Assignment Source Code

Alright ladies and gentlemen, it’s time to put your knowledge to the test!

I’ve been receiving tons of emails and comments with respect to wanting programming assignments. But I wasn’t sure exactly how I was going to go about doing it, until now.

Here’s what we’re going to do, I will outline the requirements for a practice assignment, and I will include an archive file with the contents of the assignment (at the top of this post). I will also include a video which will explain how to import the assignment into your SpringSource Tool Suite IDE and set it up so you’ll be good to go.

Sound good?

The Requirements

The assignment is to simulate the lottery. You will need to implement code that will generate 6 lottery numbers between 1 and 49 (inclusive), you will then need to implement the code that will read in 6 numbers that you will type into the console yourself. Then the numbers you input will be compared against the randomly generated lottery numbers and it will output which numbers match (if any).

Here’s the catch, you will need to make sure there are no duplicate numbers (either when being randomly generated or inputted in the console). It’s just like a real lottery after-all!

Video Explanation on How to Import the Assignment

Here’s a video that will explain how to import the assignment into your IDE.

Top 7 Tools Java Professionals Use Daily
The best part is, 85% of these tools are FREE
Download this 1-page PDF that will show you exactly how to get your hands on all these tools today.

{ 28 comments… read them below or add one }

Bernd December 22, 2012 at 5:08 am

Thank you, Trevor! Very good and interesting starting assignment.
It took me about 30 minutes to get the unit tests run sucessfully, but then I had a hard time to figure out where to enter the numbers ;-)

But I still have two unsolved problems:
1: Why do you declare a return type of Set (which is an interface only) but use HashSets in your test code?
2: How do I catch malformed/illegal numbers from in.nextInt(). I’m not allowed to catch an IOException in promptUserForLotteryNumbers(). I don’t want a stack trace, but simply force the user to enter a valid integer between 1 and 49.

Reply

Trevor Page December 23, 2012 at 4:47 pm

Glad you got the unit tests running… good point on mentioning that you had a tough time figuring out where to enter the numbers, I should have been more explicit.

To all of those reading the comments who are having trouble figuring out how to enter the numbers, when you use the Scanner to read input, it will be read from the console window. This means that when you want to “input” the lottery numbers manually, you will need to click on the console window (to give it focus) and you’ll see the cursor blinking… simply type in your number and press enter. This number will be read by the Scanner and you’ll need to store the value into a variable for use.

To answer your questions:
1) It’s good form to program to interfaces and not concrete classes, therefore I chose the interface Set in the declaration of the method. I would refer you to this discussion in StackOverflow for more information.
2) I didn’t want to make you guys worry about handling exceptions this time through, but if you feel like it, I think you can either catch the generic Exception type, or the more specific InputMismatchException

Reply

Steve Brouillard December 22, 2012 at 10:49 pm

I can write the code to generate the random numbers (without duplicates) but am having problems trying to move these numbers into the Set. In the method generateLotteryNumbers(), I have tried using generatedLotteryNumbers.add(number) as well as generator.add(number) but this does not work. I’ve tried instantiating a new Set in the method but this does not make sense to me. I’m missing either a step or the whole boat … any hints to point me in the correct direction?

Reply

Steve Brouillard December 23, 2012 at 11:45 am

Nevermind – I solved it. :)

Reply

ALJI Mohamed December 27, 2012 at 9:59 am

excellent assignment , waiting for the next … :)

Reply

Trevor Page December 29, 2012 at 4:44 pm

Working on the next assignment right now :)

Reply

naftaly ngari February 27, 2013 at 1:03 am

you are the best tutor in programming .thank you very much . i will certainly follow you tutorials and i believe i will a good programmer.

Reply

Serraphin March 3, 2013 at 5:53 pm

Hello from London, I’ve found your java tutorial via the podcasts. Great work in demystifying this stuff, it’s definitely working for me.

Regarding this assignment, I ploughed through it and managed to get it to work. I watched your walkthrough and noticed you employed a few different methods to achieve the same results as I have. However, I want to confirm I wasn’t picking up bad habits and such…

1) The playLottery method I used the following:

// intersection of two sets
userNumbers.retainAll(lotteryNumbers);

2) The generateLotteryNumbers method I used the following:

do {
int randomInt = randomGenerator.nextInt(49);
setOfNum.add(randomInt + 1);
} while (setOfNum.size() < 6);

Thoughts?

I'm glad you used a different method though, I learned a lot (debugging window, unit tests, boolean whiles etc)

Reply

Trevor Page March 4, 2013 at 7:53 am

This code looks great to me, I’ve never used the retainAll() method before, but if it’s the intersection of two Sets, then that’s perfect.

Very well done!

Reply

cpasquini June 5, 2013 at 9:39 am

In the playLottery method example above by Serraphin, performing the retainAll method on those two Sets will destroy the userNumbers Set. A non-destructive way would be the following (refer to http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html, in the Set Interface Bulk Operations section):

//create a new Set, copying the contents of either userNumbers or lotteryNumbers
Set matched = new HashSet(lotteryNumbers);

//run the retainAll (intersection) method against the newly copied Set.
matched.retainAll(userNumbers);

You can see how this works by outputting the two sets after performing the intersection:

System.out.println(“Matched Nums: ” + matched.toString()); //Matched Nums: [35, 24]
System.out.println(“Orignal Nums: ” + lotteryNumbers.toString()); Original Nums: [8, 35, 24, 1, 49, 6]

If you don’t copy the Set before hand, you will directly modify the original set of numbers.

Reply

wessley sang May 1, 2013 at 5:29 am

give me an example of a program that use stack and queue to reverse string of characters and how it can be implemented

Reply

Funky July 11, 2013 at 2:40 am

just a suggestion but for LotteryNumberGenerator class, it might be better to use numberVariable.size()<6 rather than use a while loop. Here is my code for that function:

Set randomNumbSet = new HashSet();

Random generator = new Random();
for (int i = 0; randomNumbSet.size()<6 ; i++){
randomNumbSet.add( generator.nextInt(49)+1 );
}

Reply

Trevor Page July 14, 2013 at 10:36 pm

Hmmmm, I’m not sure if that would work well.

How does your code handle the case when a two random numbers are duplicates? If say, it randomly generates the number 5 two times, then it won’t add 6 numbers to your set (as the second time it tries to add number 5, it will discard it as it’s a duplicate)

Reply

Fatih February 11, 2014 at 4:08 pm

I think that would work well if you use it in a while loop like this:

Set firstSet = new HashSet( );

while (firstSet .size( ) < 6) {
firstSet .add((int) (Math.random( )*49 + 1));
}

Reply

daviton November 12, 2013 at 3:18 pm

Hi Trevor

I cant import the classes as you did, in order to get it i have to go very deep /PracticeAssignment1/src/net/javavideotutorials/assignment1, perhaps it has to do that i am in a MAC?

thanks

Reply

Raphael December 30, 2013 at 1:05 pm

Hi daviton,

Yes I believe this has something to do with the Mac. I couldn’t import this into my Mac either but it imports fine on a Windows machine.

Reply

Durim November 29, 2013 at 3:27 pm

Thank you so much Trevor for this assignment!

I really enjoyed it :D

Reply

Raphael December 30, 2013 at 1:15 pm

Hi Trevor,

Thanks for creating this website. It’s fueling my passion to learn programming. :)

I was wondering where these assignments would fit into your curriculum. I’m not a programmer and haven’t completed the video tutorials / podcasts / blogs (probably just 25% in) and I’m having a difficult time with this assignment. I can do some of the beginner exercises in other sites (thanks to your tutelage). I was wondering if your assignments are more on the intermediate level or for someone that has already completed all the training you have developed?

Thanks for your help.

Reply

Trevor Page December 30, 2013 at 2:21 pm

The assignments are littered throughout the video tutorials course. You’ll see them appear below the videos under the heading “Homework” or “Assignments” when you’re logged into javavideotutorials.net.

In general, I’ve had feedback that my assignments are indeed quite tough. In 2014 I plan on creating a LOT more assignments and having them be a bit less challenging at the early stages for beginner programmers.

Reply

Raphael December 30, 2013 at 2:44 pm

Thanks Trevor and keep up the great work!

Reply

Ivan Lerner May 22, 2014 at 9:25 pm

Hy Trevor,
When making the first assignment, I came up with this way of testing if the input was valid inside a for loop. My question is: is it ok to mess around with the i variable that commands the for inside of it like I did? It seems to work fine, but I want to be sure.

public Set promptUserForLotteryNumbers () throws IOException
  {
	  int i, j;
	  Set user_numbers = new HashSet();
	  Scanner in = new Scanner(System.in);
	  for(i = 0; i < 6; i++)
	  {
		  j = in.nextInt();
		  if((j < 49))
		  {
			  System.out.print("Invalid number, pick a number between 1 and 49: ");
			  i--;
		  }
		  else if(!user_numbers.add(j))
		  {
			  System.out.print("Number already picked, pick another number: ");
			  i--;
		  }
	  }
	  in.close();
    return user_numbers;
  }

Thank you.

Reply

Trevor Page May 23, 2014 at 6:50 am

Yes, I think that could work as well, it’s possible to manipulate the “counter” variable in the for loop, but I don’t think it’s a recommended practice.

The reason why this isn’t a recommended practice, is that you’re essentially mimicking the functionality of a while loop through the manipulation of the counting variable (eg. i--).

The tricky part when it comes to coding is that there are often many many ways of solving a problem, but there are only a few ways of solving it well

Reply

joe May 30, 2014 at 3:02 pm

How about this?

      for(i = 0; i < 6; i++)  
      {  
        while(true)
        {
          j = in.nextInt();  
          if(j > 49 || j < 1 )  
          {  
              System.out.print("Invalid number, pick a number between 1 and 49: ");  
              continue;
          }  
          else if(!user_numbers.add(j))  
          {  
              System.out.print("Number already picked, pick another number: ");  
              continue;
          }  
          break;
        }
      }

Reply

Trevor Page May 31, 2014 at 9:13 am

I believe that looks good Joe

Reply

John May 31, 2014 at 9:02 am

Thanks Trevor for a great assignment.

I had been scooting through the internet for the past month looking for decent training for java and stumbled on your podcasts (which are great btw) where you mention your site. Decided to take the plunge into a membership with you and, considering I’m a total java noob I’m extremely happy with what you offer. Great value for money. Thanks again.

Regarding the assignment, once I got stuck it I found I couldn’t stop myself tweaking my code, trying to cater for various user input error checking. Didn’t think I would have enjoyed it so much! I love your test environment. I had a little trouble overcoming the playLottery.java file but with a sneak preview of your reveal video I got there in the end.

Looking forward to Assignment 2. :)

Reply

Trevor Page May 31, 2014 at 9:16 am

Great to hear John, and keep in mind that I made these assignments quite challenging on purpose, so you are meant to feel a bit overwhelmed… but you always have the safety net of peeking at the solution. Just be sure that you are positive that you are out of ideas before you peek… I often find that walking away from a problem for either a few hours or an entire day will allow me to come back and solve it.

Reply

manikantha July 20, 2014 at 1:31 am

Assignment: Job Tracking System
Assignment: Job Tracking System
Your assignment is to track the corporate careers of some up-and-coming executives who are
busily changing jobs, and, of course, getting paid.
In this version of the corporate world, people wither belong to a company or are unemployed.
The list of people the program must deal with is not fixed: initially there are none, and new
people may be introduced by the JOIN command. (see below).
An employee’s salary is $10000. Unemployment people draw $700 in unemployment
compensation.
Input
1.
From file “company.txt”: The company names are listed one per line. There are
at most 20 companies. Company names are at most 10 characters and do not
contain embedded blanks.
2.
From the keyboard: Commands, as listed below. and names
are at most 10 characters and do not contain embedded blanks.
JOIN
joins the specified . This may be the first reference
to this person, or he or she may be unemployed. The person does not
currently belong to another company. Remember that when a person joins
a company.
CHANGE
quits his or her job and joins the specified new . You
may assume that the person is currently employed. This command does not
tell you the person’s current employer; you have to search the data
structure to find the person.
QUIT
quits his or her job and becomes unemployed. You may assume
that the person is currently employed.
PAYDAY
Each person is paid his or her salary ($5000). (You must keep track of
the amount each person has earned from the start of the program).
EMPLOYEES
The current list of employees should be printed for the specified
. The employees must be printed in order of their name.
UNEMPLOYED
The list of unemployed people should be printed.
DUMP
Print the employees in each company, as specified under the EMPLOYEES
Assignment: Job Tracking System
command above, then print the unemployed people. Label the output
appropriately.
END
Stop accepting commands.
Ouput
After all the commands have been processed, write a list of employees to a file “employee.txt”.
The list consists of all the people who have been mentioned in any command and the total
amount of money they have been accumulated.
The following are some sample data”
file Company.txt
Borland
Microsoft
IBM
Intel
Compaq
NEC
Oracle
Commands from keyboard:
JOIN David IBM
JOIN Peter Intel
PAYDAY
CHANGE Peter Microsoft

Reply

Trevor Page July 21, 2014 at 8:52 am

Hi there Manikantha,

If you’re looking for help with your assignment, I’d suggest taking a look at Coders’ Campus, in that community you will be able to get the help you need with completing that assignment

Reply

Leave a Comment

Powered by sweet Captcha

Previous post:

Next post: