Programming a Number Guessing Game - Java Fundamentals

Programming a Number Guessing Game - Java Fundamentals


Programming a Number Guessing Game - Java Fundamentals

Remember as a kid when you played “guess a number between 1 and 10”? In this video we’ll program some Java code that simulates playing that game!

My name is Will Tollefson, I’m here to teach you key skills that will help you land your first programming job or stay current and competitive for those promotions in your current job. Subscribe to my channel and I’ll help you grow in your programming skills, and make your career soar!

Join me to learn computer programming in an easy to learn way, with a teacher who isn’t talking over your head. Or sounds like this. But instead explains things in a way you can understand.

I’m a software engineer in industry who has been coding for over a decade now and my motto is Never Stop Learning. I can give you insight into skills that employers actually care about as in addition to being a programmer I also have hired software engineers.

Ring that notification bell so you never miss fresh content that just might help you with your current programming bug.

I have experience with various types of programming such as mobile phone apps, scientific computational modeling, and embedded communications systems, to name a few, and I’ve worked on teams ranging from one to over one hundred programmers.

The content I’m offering you is free, self paced, and practical for computer programming jobs. I’ll teach you skills you need to be competitive.

Let’s dive into programming concepts like algorithms and data structures that are mostly language agnostic.

If you’ve got ideas of topics or a programming dilemma you want me to cover, drop me a comment! I’ll be efficient with your time so without further ado, let’s get to it!


Content

0 -> hi everyone today we're going to be programming a  basic number guessing game within Java it's going  
5.4 -> to be building off of some of the things that  we've done in our previous videos where we take  
9.72 -> user input and we manipulate it as a kid you  probably played the game hey can you guess a  
15 -> number between 1 and 10 or 1 in 100 and then you  had to guess a number and then the person thinking  
21.66 -> of the number would tell you higher or lower and  then you would adjust your guess accordingly we're  
25.56 -> going to go through how to program that today in  Java what we're going to do is we're going to use  
30.48 -> a scanner class like we did in a previous video  and then we're going to also introduce these other  
34.86 -> concepts of flow control so let's say that you  want to only execute certain code when a condition  
41.76 -> is true or let's say you want to execute some  code repetitively we're going to talk about how  
46.62 -> you do that with if else if else cases and while  Loops respectively so without further Ado let's  
53.88 -> get into the code all right I've got the IntelliJ  IDE up and I'm going to select a new project and  
59.58 -> we're going to call this number guessing in the  code directory add sample code all right that  
66.48 -> generated a main class for us with the normal  system.out.printline that I'm going to remove  
73.62 -> so the first thing we're going to do is when  you play the number guessing game you've got  
77.4 -> two people you've got the person thinking about  the number in their head and then you've got the  
81.72 -> guesser so let's figure out what the number that  a player one is going to have in their head we  
88.92 -> could just do something like the program always  knows what it is let's say it's always 10. but  
96.54 -> let's make it a little more interesting in that  let's make this random so that whenever you play  
101.46 -> the game over and over again if you're playing  against yourself it actually stays interesting  
105.66 -> we're going to create a random number how do you  do that well similar to how we use the scanner  
111.48 -> class what we're going to do is we're going to  use the random class that comes in the Java util  
117.06 -> package and we're going to create a random number  from it so you can see here it highlighted Java  
122.76 -> util random that looks good so I hit enter there  and that automatically imported the class for us  
129.24 -> we're going to go ahead and name this random data  
133.68 -> and remember that we need to set it equal  to something because what this is doing  
137.52 -> right now is it's only declaring that we have  a variable and not actually giving it a value  
142.56 -> so now I'm going to give it uh that Constructor  random I'm going to make a new random instance  
151.44 -> that now is held in random data so now I want to  generate a random integer with this random data So  
158.28 -> Random data dot next int now if I hover over this  IntelliJ will give me some information on what  
165.66 -> that next in method is doing for us right here  this is basically specifying that you could return  
172.74 -> any integer value well if I'm playing a number  guessing game I'm not going to be able to easily  
177.66 -> guess something within the realm of a couple  billion I would rather guess within something  
183 -> that I would find a reasonable range so maybe one  to a hundred something like that so this actually  
189.96 -> isn't the function I'm looking for so I'm going  to go ahead and look for a different function  
196.14 -> if I search down on next interior I see two  other hits that look interesting this first  
202.56 -> one that says bound and then the second one that  says origin and bound this one looks a little more  
208.38 -> promising so I'm going to go ahead and do that  one and now I'm going to put in some numbers  
214.38 -> origin of one bound of a hundred now if I read  this now this is saying that I'm returning a  
221.88 -> pseudorandom generated integer value between  origin inclusive and bound exclusive so when  
230.22 -> you play a number game like guess a number between  1 and 10 it's kind of up to you whether 1 and 10  
235.92 -> are included in there I would normally think  that they would be so if I want to go from 1  
241.5 -> to 100 I actually want to do a hundred plus  one because then that would allow the random  
247.38 -> number generator to actually generate a value  of 100 out of this so now that I am generating  
252.9 -> a random integer I need to actually store the  value of it notice that this next int function  
258.18 -> it says it's public which means I can access  it and then it says in right here that means  
263.28 -> that the return of the function is an integer so I  need to capture the return value of this function
271.98 -> like that so we started writing a few lines  
274.62 -> of code let's go ahead and  document this with a comment
281.52 -> generate the target number and I actually  don't really like the variable name random  
286.86 -> number I'm going to go ahead and call it Target  because that's the target number that player two  
291.36 -> should be guessing I want to test to make sure  this code is working properly so I'm going to  
296.16 -> type S out which is that shortcut for printing  something to the console I'm going to print out  
302.16 -> my target variable I'm going to go ahead and  run this a few times and make sure that I am  
306.78 -> getting numbers in the range that I would expect  okay so first time it was 93 second time it was  
312.3 -> 41 third time it was 92 fourth time it was 87.  technically there is a little Nuance it's called  
318.42 -> pseudo random number generation that's out of  the scope of this video talking about what's  
322.8 -> a pseudo random number generate versus a random  number generator but for all intents and purposes  
327.6 -> this is generating random data for us within  this range of values cool so now the random  
333.18 -> number generator is working let's try to prompt  the user to guess what that random number is  
339.06 -> I'm going to go ahead and ask guess  a number between okay so now that I'm  
346.56 -> adding format specifiers I need to go to  the print formatted function and percent d
356.94 -> so now um I could go in and duplicate these  variables but I don't want to do that because  
365.64 -> now what happens if I want to change this from 1  to 100 to 1 to 90. now I have to know two places  
372.78 -> in the code where I would go in and change that  value I don't want to do that I want to create  
378 -> variables for this so I only have to store it in  one place I'll do that in lower equals one and  
386.82 -> upper equals a hundred now the only thing we have  to do is in the bound since the bound is exclusive  
397.86 -> in the next int function we have to still add  one so that we can guess the upper bound exactly
406.32 -> all right now let's go ahead and run this and make  sure this still works all right cool so now it is  
410.46 -> prompting us asking for an arm between one and  a hundred but it's not actually waiting for us  
415.26 -> to enter anything this is where we need to use  the scanner class that we did last time so we're  
421.14 -> going to type scanner hit enter to import it and  we're going to set this equal to a new scanner  
428.58 -> instance over system.in just like we did in the  previous video if you have any questions on how  
433.14 -> that works go ahead and check out that video now  we're going to get the next integer and we're  
440.34 -> going to store that into a variable that we're  going to call guess now let's go ahead and print  
446.76 -> out the guess and the target another shortcut  if you want to print a formatted string in  
451.2 -> IntelliJ right away is instead of s-o-u-t it's  s-o-u-f let's print the guess and the target
463.2 -> and run this code okay so I guess a number between  100 I'm going to go ahead and put 90. oh actually  
468.6 -> it wasn't all that far off my guess was 90 whereas  the random number generator generated 80 there  
475.2 -> but it's not telling me that I got the answer  right or wrong necessarily in a message it's  
479.94 -> just saying here are the numbers so let's  go ahead and make a conditional logging  
485.22 -> statement if we were right or wrong what we  do is this is now some of the flow control  
491.34 -> logic that we haven't looked at very much  yet we do what's called an if statement  
495.78 -> if we add parentheses for the condition that  we're testing this is a Boolean expression  
502.32 -> kind of like how we talked about booleans and  the Primitive types of video we need to provide  
506.58 -> the if statement and expression to evaluate if the  statement is true we will go and execute the code  
513.6 -> if it's false we will not execute the following  code so we're going to check is is our guess  
519.48 -> equal to the Target value now one thing you'll  note here is that single equal sign we use  
526.74 -> that when we want to create what's called an  assignment we're assigning a variable to a value  
533.28 -> when we have these two equal signs sometimes  called double equals or equals equals  
538.86 -> what that means is that these values  need to be exactly the same they look  
544.26 -> at equality so let's say these were the same  I'm going to go ahead and print out correct  
551.28 -> but what if they weren't the same I can type  else and everything within these brackets  
559.32 -> will indicate what I execute when the statement  is not correct let's go ahead and run this I'm  
566.22 -> going to go ahead and August 34 this time  well no I wasn't right 29 versus 34. I'm  
572.16 -> actually kind of close guys I got off by 10  the first time and off by five the second time  
577.62 -> maybe after a while I'll be able to guess it right  on but it's not very fun if I have to rerun the  
582.36 -> program every single time I make a guess so why  don't we make this a little more interesting  
587.34 -> we'll now add the concept of continuing to Loop  through certain parts of the code until our guess  
594.78 -> is correct so how we're going to do that is  we're going to add what's called a while loop  
600.36 -> the general concept of a while loop is you  add a condition just like we added a if check  
607.98 -> that had a Boolean expression within the  parentheses anything that exists within  
614.16 -> the brackets keeps getting executed as  long as the Boolean expression is true  
618.9 -> so this code actually could be a real problem  because this will infinitely Loop forever and  
624.84 -> never leave you can even see that IntelliJ is  giving us a warning about that while statement  
630.24 -> cannot complete without throwing an exception  so now what we want to do is we want to make  
634.44 -> this Boolean expression something that  can change within the body of our Loop  
639.84 -> so if I'm playing the game I want to keep  playing until I guess the right number right
645.96 -> so you might initially think okay what if  my case is while guess equals Target but  
652.56 -> hold on you want to loop as long  as guess is not equal to Target  
657.54 -> so the way that you indicate not equal is  you throw an exclamation point in front of it  
664.5 -> this means I'm going to Loop in here forever  until guess exactly equals Target but I still  
671.4 -> have a few problems here this is indicating that  it can't resolve gas and that's because my guess  
676.86 -> variable is down here I'm going to go ahead and  do a keyboard shortcut I'm going to do on Windows  
681.18 -> shift control up Arrow and that moves a line of  code up so now it knows what the guess variable is  
689.46 -> and I have the target variable but I'm not doing  anything in the while loop So within the bounds of  
694.38 -> this Loop guess and Target are never changing so  again this is going to be an infinite while loop  
699.54 -> so let's go ahead and prompt the user each  time within the loop to guess a new number  
706.08 -> basically I'm going to want this code within my  Loop but I've got a problem here because I already  
712.38 -> defined what guess is up here so I'm actually  going to just declare the guess variable without  
720.84 -> assigning it a value and then in here I'm going to  assign it a value but you'll notice that the while  
726.24 -> loop actually doesn't like that it's saying I have  a guess variable but I haven't initialize it to a  
730.8 -> value the reason that that's important is because  when you have a local variable like guess how Java  
736.5 -> works is when you don't assign a particular value  to a variable it uses whatever was the default  
742.62 -> value at that memory location that the variable  is pointing to which means that this could be  
748.74 -> literally anything and there is a tiny tiny chance  that you could happen to have your guess variable  
755.1 -> actually equal Target before you even enter  this Loop so that's what this is telling you  
759.84 -> so I'm going to go ahead and have this so that it  shouldn't equal Target with my current code I know  
765.36 -> that Target has to be in range lower and upper so  if I put a 0 there I know that it's never going  
771.6 -> to exit this while loop immediately without  ever executing it so now if we run this code  
777.18 -> waiting's gonna happen I'm gonna go  ahead and guess the number I'll guess one  
781.26 -> okay my program seems to just be sitting  here it's not doing anything what's going on  
787.26 -> I just keep entering numbers okay nothing's  happening so if you think about it we're in  
792.42 -> this Loop we're making guesses as long as guess  is not equal to Target we're just going to keep  
799.26 -> asking for the next integer from the user  input variable which is reading system.in  
806.88 -> I'm not actually telling the user hey your  answer was wrong guess again so I'm going  
811.44 -> to go ahead and update this code to do that  so let's check if it was the correct number
817.86 -> guess equals Target
825.24 -> correct otherwise if it wasn't then the  likely event that the guess was wrong  
832.14 -> you could say guess again so I'm gonna  go ahead and stop the existing program  
836.52 -> and I'm going to try running it again  how's this look guess again okay  
844.44 -> so now we're getting somewhere here but typically  how the game works is player one knows the number  
850.44 -> and is giggling thinking oh hey you don't  know my number yet and player two is kind of  
854.52 -> all right you know give me a hint so player one  says okay you gotta go higher or lower so then  
859.14 -> player one can hone in on the area to look  for so let's go ahead and update that next  
865.14 -> if guess equals Target we are correct otherwise  we're going to add what's called an else if  
873.9 -> so now we add another Boolean expression get  gas is greater than Target you might remember  
881.82 -> greater than or less than signs from math class  another thing you can do is you can do an equal  
889.5 -> sign but we already know that guess doesn't equal  Target from this Boolean expression above so I'm  
895.68 -> going to go ahead and do that guess is equal to  Target guess is greater than Target in this case  
905.76 -> so now we want to guess a lower  number because our guess is too high
911.76 -> now the only other case we can  have if the number isn't equal  
915.84 -> and it's not greater is that it is less than  so you might think okay I would just write  
920.64 -> guess less than Target I know you could  but that's already implied based off of  
927.54 -> these previous two Boolean expressions so  you can actually just change this to else
936.36 -> I want to guess higher let's go ahead and stop  this program and run it again all right so now  
942.66 -> that I know that I have a number to guess and I  get a higher or lower indication I can use binary  
949.44 -> search so I'm going to put my number right in  the middle now I know that is definitely less  
953.34 -> than 50. so now if I break that in half again I'm  going to guess 25 . so now it is somewhere between  
959.4 -> 25 and 50. so let's try 37. okay now we're really  narrowing down where this could be how about 30.  
969.12 -> all right how about 33. there we go all right the  end number was 33 very good so this is an initial  
976.98 -> take at how the code could work now let's go in  and make some adjustments to it so first thing  
982.14 -> I'm going to do is what am I doing throughout  the branching logic of my code and how can I  
986.58 -> go ahead and clean it up it's good to always  comment your code fine upper and lower bounds
1000.2 -> now this code is ask user for first input
1009.14 -> I don't really love this while loop  problem I have with this code is that  
1016.28 -> if I set guess equal to zero what happens if  I do something maybe that I shouldn't do and  
1024.2 -> I guess a lower bound of zero and an upper  bound of zero if I run this code you'll notice  
1033.5 -> that my logic breaks down a little bit uh oh  if I guess a number between zero and zero it  
1039.44 -> already says correct and then it prints out  the guess and Target without doing anything  
1045.44 -> now this is a bit of an edge case you probably  won't play a game with somebody where you're  
1049.82 -> guessing between the same number but let's go  ahead and switch it up let's do zero and one  
1057.44 -> now this time the code looks like it's going  to work fine I know that the answer has to be  
1061.7 -> one because the code checks for if guess is zero  first so if I run this enough times I will hit  
1069.98 -> the situation where it guesses zero immediately  and here it is right here so this is an example  
1076.04 -> of where I've got code here that makes certain  assumptions and I've got code here that makes  
1081.74 -> certain assumptions and I need to figure out  how to make those assumptions align correctly  
1086.54 -> but the main problem I was running into was  that I had to initialize the guess variable  
1092.78 -> before I could do it in this wild Boolean  expression there's a way around that and  
1098.6 -> that's via what's called a do while loop  so I'm going to go ahead and change this
1106.28 -> into what's called a do wire Loop the main  difference between while and do while is that  
1113.24 -> while if the expression is evaluated at the start  and it is already evaluated to false then you  
1121.58 -> won't even enter the loop if you have a do while  you guarantee running the loop code at least once  
1128.18 -> so now I don't have to give guests an initial  value now the next thing that I notice is that  
1136.04 -> when guessed exactly equals Target I get told  correct but I'm already checking that here  
1143.84 -> oh and also there's no way this else case can  even exist because the while loop is verifying  
1151.28 -> that it keeps looping until guests equals  Target so these are actually not necessary  
1159.14 -> but I'm going to change the logic a little bit  I want to limit how big my do while loop is  
1166.1 -> so I'm not going to check if guess  equals Target all that I'm going to do  
1172.46 -> is check if guess is greater than  Target or gas is less than Target
1181.52 -> so now what this did is I know for a fact  guess has to equal Target to leave the loop  
1189.56 -> and the implied else case here is that guess  equals Target so I don't even need to print  
1194.84 -> anything I already know what the case is and  sometimes people might want to add a line of  
1200.24 -> code explaining that so how the code is written  there's no way I can leave this while loop without  
1205.28 -> verifying that this condition is true that's  not always the case when you talk about break  
1210.26 -> statements and exceptions but that could be a  topic for a future video but for now I know that  
1218.54 -> this is correct and I don't really need to  indicate my guesses anymore so I'm actually  
1224.78 -> going to delete that line as well all right so  one last thing that I'm going to mention quickly  
1229.52 -> is that the scanner class does have that close  function and a scanner is done close it now in  
1241.4 -> my previous video I closed it and that was because  I knew that it was the end of the main function we  
1246.14 -> were done with our code this time I'm not going to  close it because I'm going to show that the code  
1249.86 -> works just fine without that and in some cases  if there were more code after this that needed  
1256.7 -> the system.in resource then you would actually  have an issue where your scanner already closed  
1263.6 -> it and now you can't open it anymore so there are  things to think about of when you close a scanner  
1268.04 -> and this time I'm just not going to close it just  to give an example of how this still works and  
1272.36 -> I forgot to change the range onto something  that's actually more of a fun guessing game  
1277.7 -> I'm going to change this from 1 to 10 and  run it again all right look at number seven  
1283.4 -> nope one right there how about four cool all right  very good so the last Edition we're gonna make to  
1290.06 -> this code is something that's actually near and  dear to my heart and that is friendly competition  
1293.72 -> among friends let's say you've got two or three  friends that are all playing this game how quickly  
1298.94 -> can you guess the resulting number so to do that  we're gonna make a counter variable that we have  
1304.82 -> to initialize outside of the loop because  we're going to use it after the loop is done  
1310.64 -> uh we'll go ahead and set it to a value of  zero because we haven't made any guesses yet  
1314.6 -> then after each guess attempt we're going to  increment our counter this little plus plus  
1320 -> is indicating that you want to add one  onto the value of the counter variable  
1325.34 -> so it's going to be 0 here we're going  to make a guess and then it'll be one  
1329.42 -> and that is the fastest that somebody could  guess this let's update our print statement
1338.12 -> it took you  
1341.66 -> that many tries the reason I'm not doing a  formatted string here just because I've got the  
1346.58 -> one variable and I think this is plenty readable  you can go ahead and do a formatted string or you  
1352.04 -> can do print line like I've got here all right  so I'm gonna go ahead and try this out it's not  
1358.22 -> a three that means it has to be either a one  or a two okay very good that was only two tries
1366.38 -> how about this time nope no okay and that took  me four tries so you can see with not a lot of  
1375.38 -> code you actually can make a fun game and you  can play with your friends and while you're at  
1380.9 -> it you can show your friends how to write Java  code and hey maybe even introduce them to a  
1385.34 -> video like this I'd really appreciate it guys  and that's all there is to it you've written  
1390.32 -> another Java program go ahead and check that  as another thing you've done on your list on  
1394.82 -> your journey to learning more about Java  congratulations if you like this video or  
1398.84 -> want to see more of that type of content  please take a note to like the video and  
1403.88 -> write a comment if you found this interesting  if you're enjoying the channel content you  
1407.84 -> haven't hit that subscribe button please do take  a moment to do that I really appreciate it well  
1413.42 -> that's all I've got for today hope you guys have  a great day and I'll see you next time take care

Source: https://www.youtube.com/watch?v=siogd21nVL4