≡ Menu

Java Practice Assignment #1

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.

{ 36 comments… add one }

  • Bernd December 22, 2012, 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.

    • Trevor Page December 23, 2012, 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

  • Steve Brouillard December 22, 2012, 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?

    • Steve Brouillard December 23, 2012, 11:45 am

      Nevermind – I solved it. :)

  • ALJI Mohamed December 27, 2012, 9:59 am

    excellent assignment , waiting for the next … :)

  • naftaly ngari February 27, 2013, 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.

  • Serraphin March 3, 2013, 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)

    • Trevor Page March 4, 2013, 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!

      • cpasquini June 5, 2013, 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.

  • wessley sang May 1, 2013, 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

  • Funky July 11, 2013, 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 );
    }

    • Trevor Page July 14, 2013, 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)

      • Fatih February 11, 2014, 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));
        }

  • daviton November 12, 2013, 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

    • Raphael December 30, 2013, 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.

  • Durim November 29, 2013, 3:27 pm

    Thank you so much Trevor for this assignment!

    I really enjoyed it :D

  • Raphael December 30, 2013, 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.

    • Trevor Page December 30, 2013, 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.

      • Raphael December 30, 2013, 2:44 pm

        Thanks Trevor and keep up the great work!

  • Ivan Lerner May 22, 2014, 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.

    • Trevor Page May 23, 2014, 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

  • joe May 30, 2014, 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;
            }
          }
    
  • John May 31, 2014, 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. :)

    • Trevor Page May 31, 2014, 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.

  • manikantha July 20, 2014, 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

    • Trevor Page July 21, 2014, 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

  • Bryan August 20, 2014, 1:09 pm

    Hi Trevor,

    Quick question — in your test code, I noticed this:

    int lowest=49;
    int highest=1;

    … later on you assert:

    assertThat(highest, is(49));
    assertThat(lowest, is(1));

    — which seems to contradict the the values you set to the variables. Am I missing something here? Or is this a typo?

    Love your podcasts — about half-way through them. Thanks for the inspiring content!

    Oh one thing — I’m an android listener — I know you mention 5 star reviews, etc., on itunes — but is there a way to give your podcast a bump on other platforms? I would certainly give you one!

    • Trevor Page August 21, 2014, 10:11 am

      This is indeed the correct code. I don’t want to spoil the surprise as to why the values are set up like this. If after you’ve looked through it and are still having troubles finding out why I set the initial values to the “flipped”, let me know and I can explain.

      • Bryan August 21, 2014, 4:31 pm

        Cool. I think I grok it now. I am really rusty with Java, so this homework is proving to be a challenge to me — but when I get a part completed… the satisfaction feels great. I also appreciate the focus on unit testing.. I’ve done hackish coding for close to 20 years…. mostly in perl/bash.. but in recent years with java and groovy — but never with any real unit testing. I am having to shake things up mentally to approach it this way, but I am glad you are giving me a means to do so. Thanks again!

  • Bryan August 21, 2014, 10:44 pm

    Hi again Trevor,

    I kept looking at that unit test — the one for testing 1-49 number values — and I think I get it.. but I am also a little confused. Correct me if I am wrong, but is this some sort of shuffle approach (for lack of a better term)? Seems to work great… *if* you have sufficient number of iterations in your test. Given that a piece of code is good, shouldn’t a unit test always pass , regardless of doing 100000 iterations, or 1000, or 10? For example, if I reduce the iterations in your test to a smaller number, and all 6 numbers generated are between 1-49 inclusive… the test fails a lot… guessing because it doesn’t have enough data to do the number shuffle trick? If I am missing some integral kernel of truth, let me know. I’m curious why this approach was taken… computational efficiency? Best practice? I honestly am curious. Thanks!

    • Trevor Page August 25, 2014, 7:39 am

      You are 100% correct in your assessment of the situation. We are using a large number of iterations to guarantee that the test will always pass (through statistical probabilities, the test should always pass). If you reduce the number of iterations, then it will start to fail more and more frequently.

      The trade-off I made here was to use up slightly more CPU cycles in favor of lots of iterations, as opposed to a more complicated coding approach that used far less CPU cycles. Either approach would work, but I made a decision that the length of time it took to complete my particular solution was acceptable.

  • Bryan August 22, 2014, 12:12 pm

    By the way — finished this assignment. Learned some great tricks (especially re: retainAll() set method). This is the perfect level of difficulty — on par with Java I encounter at work. Appreciate the challenge!

  • Matt October 13, 2014, 12:42 pm

    Thanks for the podcast and assignments, Trevor! You’re doing great work and I really appreciate it.

    A note for IntelliJ IDEA users who are having trouble with console input:
    The default JUnit test configuration does not allow input to the console, so the play_lottery test just spins waiting for input. I replaced the play_lottery test in PlayLottery with a public static void main() method and it worked fine.
    https://stackoverflow.com/questions/26092784/reading-system-in-for-intellij-using-console

Leave a Comment

Powered by sweet Captcha