≑ Menu

Java Practice Assignment #1

Before You Start

There’s one important data structure you need to learn about first before you begin this assignment.

It’s not required that you learn this new data structure, but it will help with this assignment.

To learn about it, just watch the video below:

The Code You’ll Need

I’m hosting the source code that you’ll need to download on GitHub.

You can view the GitHub repository here

But to actually transfer these files into your own IDE, you’ll need to follow the instructions in the video below.

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 a way to download the files via GitHub. 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.

GitHub Repository URI: https://github.com/tp02ga/JavaPracticeAssignment1.git (You’ll want to copy paste this into your IDE when you’re cloning my GitHub Repository)

{ 75 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 … πŸ™‚

    • Trevor Page December 29, 2012, 4:44 pm

      Working on the next assignment right now πŸ™‚

  • 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

    2) The generateLotteryNumbers method I used the following:

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


    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.

        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));

      • ajibigad December 11, 2014, 12:35 pm

        I think it should work well Trevor.
        and @Funky , the for loop isn’t really required
        this works too..
        Set randomNumbSet = new HashSet();
        Random generator = new Random();
        int i=0;
        if(randomNumbSet.add( generator.nextInt(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?


    • 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 πŸ˜€

  • 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: ");
    		  else if(!user_numbers.add(j))
    			  System.out.print("Number already picked, pick another number: ");
        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++)  
              j = in.nextInt();  
              if(j > 49 || j < 1 )  
                  System.out.print("Invalid number, pick a number between 1 and 49: ");  
              else if(!user_numbers.add(j))  
                  System.out.print("Number already picked, pick another number: ");  
  • 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
    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.
    From the keyboard: Commands, as listed below. and names
    are at most 10 characters and do not contain embedded blanks.
    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.
    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.
    quits his or her job and becomes unemployed. You may assume
    that the person is currently employed.
    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).
    The current list of employees should be printed for the specified
    . The employees must be printed in order of their name.
    The list of unemployed people should be printed.
    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
    Stop accepting commands.
    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
    Commands from keyboard:
    JOIN David IBM
    JOIN Peter Intel
    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.

  • Izzy Ali February 1, 2015, 7:12 am

    Thank you very much for assignment, Im so rusty with Java at the moment and I thought I would jump back in.
    This is the code I have created for the method for generating the lottery numbers, I feel like it is right but for some reason the generate number JUnit test comes up with red, I haven’t used Junit before do I need to change something?

    public Set generateLotteryNumbers ()
    Random randomGen = new Random();

    Set lotteryNumbers = new HashSet();
    while(lotteryNumbers.size() < 6)
    //Create a random number between 1 & 49
    Integer randomNumber = randomGen.nextInt(49) + 1;
    return null;

    • Izzy Ali February 1, 2015, 7:18 am

      Ahh I figured it out, I was returning null that’s embarrassing.
      I was wondering is this website and Trevor still active? I haven’t seen an update since Octtober

      • Trevor Page February 7, 2015, 11:08 am

        Whoops… I just posted my guess in your other thread then saw this post. Glad to see I had the right answer (still got it!)

        As for new material, I will be continuing to write new articles in the near future. I’ve been extremely busy with the “business” side of things lately trying to get everything sorted so that I can free up more time to create content.

        Basically that means that I’m hiring people right now to help me automate everything I do.

        My goal is to get back to creating content no later than April 2015

    • Trevor Page February 7, 2015, 11:05 am

      I think it’s because you’re returning null, you should be returning the Set (lotteryNumbers)

  • Brittany April 29, 2015, 10:44 pm

    After which video tutorial would you suggest attempting this assignment? Also, I use JGrasp and Xcode for IDEs. I’m lost just on the import portion. For your tutorials, should I just download and use SpringSource Tool? I feel like this will save me a lot of trouble. Thoughts? BTW, I am accessing this assignment because I answered a survey for you, and I am currently only watching the video tutorials that I receive via email. Loving your stuff though!

  • Lee July 11, 2015, 8:03 pm

    this is very frustrating, i have no idea where to start. why would i know how to do this –

    this method should pull input from the user in the console. It should
    * gather 6 Integers from the user and then store these numbers in a Set of
    * Integers that will then be returned by the method.
    * Hint: use the following code to get numbers:
    * Scanner in = new Scanner(System.in);
    * in.nextInt();

    we have not discussed anything like this in the tutorials and now you think i can just pull this out of thin air?
    this exercise is not helpful

    • Trevor Page July 14, 2015, 9:46 am

      These feelings of frustration are completely normal and even more intense when going through the formal education system. The professors and lecturers in the formal education system leave you even more “high and dry” and force you to learn a TON on your own.

      My approach here is to introduce a smaller amount of that same frustration here as it does help one grow as a programmer.

      Improving your Googling skills will be of critical importance when you’re a full-time programmer. When I worked as a full-time programmer, I didn’t have anyone holding my hand when I was thrown into the deep end of a massive application with over 5 million lines of code.

      I can help you out by pointing out that a Set is a type of data structure (much like a List), but the difference is that a Set won’t allow you to insert duplicates. I can also suggest that you use the HashSet implementation in this program.

      Here’s the Java docs for the HashSet data structure: http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

      If you have any specific questions, please feel free to post them in the forums.

  • Anonymous September 30, 2015, 1:19 pm

    Awesome Exercise!

  • Anonymous September 30, 2015, 1:29 pm

    There is a better way to find the matching data from two different sets.
    set1.retainAll(set2). It retains the matching data of set1 and set2 and save the matching data back to set1.

  • Anonymous October 8, 2015, 8:01 am


  • Brook Scott January 15, 2016, 10:46 am

    I’m having trouble running the unit tests. I get errors for all the assert statements. I output all the test values to the console and they appear to be correct. My program runs with no errors, I just can’t get the tests to run.

    Also, is this message a problem and if so, how do you fix it?
    java.lang.SecurityException: class “org.hamcrest.Matchers”‘s signer information does not match signer information of other classes in the same package

  • Brook Scott January 15, 2016, 12:20 pm

    Never mind, I looked it up on Stack Overflow! It had to do with the build path. I put the hamcrest jar before the JUnit4 library in the order and it worked.

  • Chad G February 25, 2016, 1:53 pm

    The first Github assignment url i try to install is failing.

    • Trevor Page February 28, 2016, 6:03 am

      Can you post a link to a screenshot of the failure you’re receiving?

  • Rober March 21, 2016, 3:10 pm

    When try to run unit test for assignment 1 i get the following error message:

    java.lang.SecuirtyException: class “org.hamcrestMatchers’s signer information does not matach signer infomration of other classes in the same package.

    How do i correct this issue.

  • Matt March 22, 2016, 10:37 pm


    I had the same issue. I tried most of the solution on this stackoverflow question


    This worked for me:
    I resolved this problem by removing Junit4 library from the Build Path and added TestNG Library to the build path and imported TestNG annotations instead of Junit4 annotations in my java program.

    You can download the jar from: http://mvnrepository.com/artifact/org.testng/testng/6.9.10, then just add it to your class path, and remove Junit from your classpath. The annotation is the same: ‘@Test’.

  • salahuddin May 12, 2016, 2:39 pm

    Hi Trevor,thanks nice interesting assignment, was able to solve it, i know it is not an elegent code , would have a look at your solution
    in the play lottery method copied both the sets to corresponding list and used the nested loop
    for (int i = 0; i <6; i++) {
    for (int j = 0; j < 6; j++) {
    {matchedset.add(lnumbers.get(i));}} }
    return matchedset;

  • Sam June 17, 2016, 1:40 pm

    all good. i finished it in 30 min and working well.. enjoyed it..

  • Fredrik July 10, 2016, 11:27 am

    Hi Trevor!

    Thank you for the assignment. It really deepened my understanding of the Set interface and the class HashSet in particular.

    I managed to solve the assignment in little under 3 hours, and at first it caused a bit of a headache πŸ™‚

    Keep up the good work!

  • Addison August 12, 2016, 6:44 pm


    I’m still having great difficulty getting the errors to resolve using JUnit with hamcrest.Matchers.is causing all sorts of errors in the test class… if you can shoot me an email or something to help with the error it’d be great.



  • Damien November 29, 2016, 3:52 am

    I’m having the exact same problem and generating the same error code.

    Are you using Springsourse Tool Suite or Eclipse?

  • Dwayne Sparks January 24, 2017, 4:17 am

    For anyone receiving the Exception:

    “java.lang.SecurityException: class β€œorg.hamcrest.Matchersβ€β€˜s signer information does not match signer information of other classes in the same package”

    when attempting to run each test case in the Tests class, as Brook Scott stated above, the issue has to do with the build path and can be resolved by moving the hamcrest jar file before the JUnit4 library in the “Java Build Path” settings. Please follow the steps below to resolve this issue.

    1) Right click the “PracticeAssignment1” project and choose “Properties”.
    2) Next choose “Java Build Path” in the list on the left of the Properties window..
    3) Click the “Order and Export” tab.
    4) Highlight “hamcrest-all-1.3.jar – PracticeAssignment1/lib” and click the “Up” button. This should move the jar file above the “JUnit 4” library.
    5) Click “OK” to save the changes and exit.

    • Shaun September 13, 2017, 7:55 am

      Hi, I have completed the assignment and it is working, is there any way to view Trevor’s solution? Just to compare methods.

  • Elena March 2, 2017, 7:37 pm

    Hello Trevor,

    I have a hard time to creating compare code for
    public Set playLottery (Set lotteryNumbers, Set userNumbers){
    So I have to compare between lottery number and user number. Can you explain more to figure out how to create it.
    Thank you very much!

    • Charles Knell July 2, 2017, 12:46 am

      You need to use the equals method of one of the Integers for the comparison.

  • Harry March 15, 2017, 8:50 am

    Hi Elena,
    You can use retainAll method to compare both the sets

    public Set playLottery (Set lotteryNumbers, Set userNumbers)

    return lotteryNumbers;

  • Harry March 15, 2017, 8:56 am

    Hi Trevor,
    i was wondering, if i can find a more useable and handy solution for below code
    Set GuessNumber=new HashSet();
    Scanner in = new Scanner(System.in);
    System.out.println(“Enter 6 numbers between 1-49”);
    int number1=in.nextInt();
    int number2=in.nextInt();
    int number3=in.nextInt();
    int number4=in.nextInt();
    int number5=in.nextInt();
    int number6=in.nextInt();


    for(int i : GuessNumber)

    return GuessNumber;


  • Colin Ifteni March 29, 2017, 10:58 am

    Hi Trevor,

    I managed to finish the assignment without noticing your Hamcrest test. Running Tests as JUnit Test was nice, but what reason was waiting for 100000 loops to finish? Therefore I edited the testing loop to 100. Was 100000 loops essential for testing?
    How can we assert that the test is successful? It just finished peacefully, without telling us of any error. No Failure trace of any kind.
    Actually, I did every part of the assignment as standalone classes, having their own public static void main() something. After having returned, and printed out, the required sets, I did the necessary clean up and run it as JUnit Test.

    • Charles Knell July 2, 2017, 12:42 am

      RE: what reason was waiting for 100000 loops to finish?

      A large number of loops is necessary so that the random number will hit both its maximum and minimum.

  • mark April 25, 2017, 4:10 am


    just wondering if there is a way to take scanner inputs and have them showing all on the same line as I’m entering my guesses. I’m not sure if this is just a command line view vs user view.

  • Bin May 30, 2017, 9:46 pm


    I don’t understand why the answer is not C, but is A. Was wondering if someone could help clarify here.

    Which of the following statements is not correct?
    You can access a non-static method from a static method
    You can access a static method from a non-static method
    You can access a static variable in a non-static fashion
    You can access a static variable in a static fashion


  • Derek M. June 9, 2017, 6:46 pm

    Hey Tpage….

    1) Your course has been super helpful so far. I am a computer science major, but am just now wanting to pursue a career in programming, so I am re-learning.

    Anyways, is it possible that our assignment 1 is working correctly, but not passing your tests?

  • Gabor June 12, 2017, 4:21 pm

    Hey Trevor,

    First of all thanks for the campus, it’s really great, i’m really enjoying it so far, and i’m really excited about the upcoming challenges.

    I had some problems with IntelliJ, cause it actually doesn’t show a console if there is no
    public static void main(String args[]) method in your code, but stackoverflow helped with that one. πŸ™‚

    What do you think about this solution for promptUserForLotteryNumbers()?
    public Set promptUserForLotteryNumbers() throws IOException {
    Set lotteryNumbersFromUser = new HashSet();
    Scanner in = new Scanner(System.in);
    while (lotteryNumbersFromUser.size() 0 && currentNumberToAdd <= 49) {
    if (lotteryNumbersFromUser.contains(currentNumberToAdd)) {
    System.out.println("Invalid number, the number has been already added!");
    } else {
    System.out.println("Number \"" + currentNumberToAdd + "\" has been added.");
    } else {
    System.out.println("Invalid number, the number is out of range (1-49)");
    return lotteryNumbersFromUser;

    Finally, it was really useful to go through the comments as well, cause first i did this:
    Set matchedNumbers = new HashSet(6);
    Set notMatchedNumbers = new HashSet(6);



    return matchedNumbers;

    then i realized, that there is a retainAll built-in function for Sets πŸ™‚

  • Andrew June 13, 2017, 1:38 pm

    Hey am having this problem while trying to compile and execute ……….java.lang.SecurityException: class “org.hamcrest.Matchers”‘s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(Unknown Source)
    at java.lang.ClassLoader.preDefineClass(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at net.javavideotutorials.assignment1.Tests.should_return_a_set_of_6_numbers_with_no_duplicates(Tests.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

    • Charles Knell July 2, 2017, 12:37 am

      See the post by Dwayne Sparks January 24, 2017, 4:17 am.

  • Tim Smart July 24, 2017, 5:03 pm

    Very nice first lesson. Not too mundane not too difficult either.

    My only suggestion is telling people how to fix things like “Dwayne Sparks” said above. My test were failing, even though had println of the “highest” and “lowest” and they were equal to 49 and 1 respectively. Once I reloaded Junit4, they started working.

  • Shaun September 13, 2017, 7:56 am

    Hi, I have completed the assignment and it is working, is there any way to view Trevor’s solution? Just to compare methods.

  • Mihai Sabadac November 14, 2017, 7:04 am

    Hey there,
    I complete the code to work (generate the numbers, read the numbers and compare the two, but the tests are still failing, and I have no more ideas what to check… Can someone give me a hint?
    The project is here:

Leave a Comment