Java Fundamentals

Random Number Array

Angie Jones

Angie Jones

Java Champion
Java Fundamentals

Check out a free preview of the full Java Fundamentals course

The "Random Number Array" Lesson is part of the full, Java Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Angie walks through creating a program that generates random numbers and inserts them into an array with a fixed length.

Preview
Close

Transcript from the "Random Number Array" Lesson

[00:00:00]
>> Angie Jones: So we're gonna write a lottery ticket program. If anyone happens to use this and they win something, they have to give me a small portion of the winnings, okay? If it's five bucks, I'll take one buck, all right? So we're gonna create a lotteries quick pick application.

[00:00:21]
It's gonna generate a lottery ticket with 6 random numbers between 1 and 69, all right, y'all ready? This should be a fun program to write.
>> Angie Jones: So let's create a new package, this one we'll call arrays. And inside of here, we'll create a new class that we're calling LotteryTicket.

[00:00:52]
>> Angie Jones: All right, so I wanna do something different with my global variables this time, I'll show you. So I'm gonna make private, I am going to use static, I'm going to use final. Well, I'm pulling out all the big guns, and I'm gonna use the data type. And then I'm gonna define this variable in all caps, and this is gonna be the length of the array, 6.

[00:01:23]
What I've done here is declare what's known as a constant. Constant means this is a variable that should not be changed, okay? It cannot be changed because I used the word final here. So this is something like, I know length will never change because the lottery tickets only hold 6 numbers.

[00:01:51]
I feel good about that by writing in all caps. When people use this later on within the same program,
>> Angie Jones: They see it in all caps, you know immediately, by just like any other convention in Java, you know what it is. All caps, that means a constant, final variable, okay?

[00:02:11]
Now, I don't have to write it like that, I could have written it all in lower case. But you lose a little bit of context with other Java developers, all right? And for those of you who code in other languages, you know that someone will have to modify this at some point.

[00:02:27]
And it's good if they're able to read it and know what's going on, right? All right, so all right, we made the length. The other constant I wanna make is the maximum number that can be on the lottery ticket. So we'll do a static final, and we'll call this one MAX_TICKET_NUMBER, and that was 69.

[00:02:57]
All right, question on constants? All right, so I made the main method, and inside of here we're going to create an array. So we'll make it of integers, we'll call it ticket, and I'm gonna call a new method that we have not written yet to say generateNumbers. Yes, question.

[00:03:27]
>> Audience: Can int[] be written as var here?
>> Angie Jones: Okay, it can if generateNumbers is written. So right now it would bark, but lets write generateNumbers, at least the header for that. So if I say public static int[] generateNumbers(){},
>> Angie Jones: And then I could say var because it will infer.

[00:04:01]
You notice there, remember someone asked, well, how will you know what it is later? You see this little gray part, so IntelliJ is telling me Java has inferred this as an integer of arrays, okay? All right, I'm gonna leave it as that because I want you to have that as an example.

[00:04:22]
Okay, so you're ready to generate the numbers? [LAUGH] So much fun. Okay, so we're are going to create a ticket in here as well. So we'll say int[] ticket =, and this time we'll say new int[]. And then we could use that length in here, right? The LENGTH constant.

[00:04:54]
>> Angie Jones: So this is another good reason to use these kinda global constant variables. Let's say the state changed lottery tickets, and now it's 5 numbers or 7 numbers or whatever, I can come in here in this one place, and I can just change it. And the whole program still works, as opposed to defining it in multiple places, they call those [LAUGH] magic numbers.

[00:05:21]
You just see random numbers somewhere, like if I would have put 6 here, it might not be clear, why did she make it 6 or whatever? And then you see it in the for loops, you see it everywhere, the number 6 just scattered all over the place. And if I needed to update this to 5 or 7, I gotta go all through the code, find it everywhere the number 6 appears, right?

[00:05:44]
Nightmare, all right? Now we're gonna use this class called Random. It is a very useful class for when you want to generate random things. So it's one of my favorite ones, especially when I'm writing games and stuff. So Random, and we'll call the variable name random, too, = new Random.

[00:06:10]
>> Angie Jones: So because Random is not in our package, we need to import it. It comes from Java.util, it's a built in Java class. And now I want to go through the array, and I want to populate it with random numbers. Because the array holds multiple values, this is a perfect use case to use a loop.

[00:06:36]
I don't want to write code that says put this in the first one, second one, third one, and then I'm basically duplicating the same code. However many times this length is, I can write the code one time within a loop. Because I know the number of times this needs to execute, what's the best loop?

[00:06:55]
>> Audience: For loop?
>> Angie Jones: For loop, very good. All right, so we're gonna say for(int i = 0, i < LENGTH, right? Yes, and then i++.
>> Angie Jones: All right, inside of here, I want to go ahead. This is getting juicy. I want to go ahead and define int randomNumber, okay?

[00:07:34]
And I'll actually say the randomNumber =, and we can use that random method. And we can say nextInt, inside of nextInt, notice there is, remember we talked about overloaded methods? So there's nextInt that takes nothing, it'll just give you a random integer. There's nextInt with a bound, so I can say up until a certain thing.

[00:08:00]
And then this next int, I'm not used to origin, let's see what this does. Range, int origin, is that like the initial number? So these little things in Java are Java docs. So if you need to know anything more about a method, usually the developer includes some Java docs that let you know what the parameters are, what it returns and that sort of thing.

[00:08:26]
So anyway, let's do nextInt, and we'll say that we want the max number as the limit, right, the max ticket number. Now, I don't know, we can test it out, if that other overloaded method, that third one, allows that origin. I don't know if that means an initial number.

[00:08:50]
If so, that would be great, because zero is included in integer numbers, and we don't want 0. We want 1, so let's try that and see if it works. Okay, maybe I can get to it now, there we go. Origin, the least value that can be returned, beautiful.

[00:09:10]
Okay, that's exactly what we want. Okay, that's wonderful. So now we have this random number, and we can add it to our array. So we can say ticket, which is the name of the array, that's how you access it. And then we wanna give it an index. So we wanna say, whatever number.

[00:09:31]
Since we're doing a loop, i is the representation of the index. So i is beautiful because it starts at 0, right? And arrays start at 0, so we can just say ticket[i], and this will be whatever number we're on in the loop, it'll add a random number to that slot, okay?

[00:09:53]
So we can say tickets[i] = the randomNumber, all right? And then outside of this loop, we can just return the array, so return ticket.
>> Angie Jones: So that's how you would set a number or whatever, set an element within an array. Basically, you would need to do the sub in an index.

[00:10:22]
Now, there's one problem with this, because we're doing random numbers, it has the possibility of doing a duplicate number, right? I don't know about you, but I'd be pretty upset if I got a quick pick lotto ticket and there's two 25s on there or something, right? No chance of winning.

[00:10:39]
So we need to add a little bit more logic here that makes sure that the number does not already exist within the array. So this is a good exercise for us to see how do I read. We just saw how to write to an array, how do I read from an array or search an array, which is a very common task.

[00:10:57]
You wanna know if something already exists within the array. All right, so we're gonna refactor this a little bit. And let's go ahead, and remember, this is, I wanna do another loop that's gonna read from the array. I'm gonna do it inside of this loop. So now we got a nested loop going on, right?

[00:11:24]
So I'm gonna say int random number, I'm just gonna leave it right there. And before I add a random number to it, I wanna make sure that that thing doesn't already exist. So we're gonna do a do while, let's do it one time. Look at us using do while.

[00:11:41]
>> Angie Jones: All right? So I'm gonna do while this number doesn't already exist, and so my condition for while would be, basically, search the ticket, give me a boolean value if it exists or not. So I'm gonna make another method here. And we'll say public static boolean search, this will take the array and then tell me the number you want me to search for.

[00:12:22]
>> Angie Jones: Now, inside of here, someone asked about for loops and how that was written and how verbose that was. There's another sort of for loop that's called an enhanced for loop, and it's perfect for dealing with arrays or collections of objects and things like that. So let's use it now.

[00:12:56]
We could have definitely used the other loop that we already know about, the for loop that we already know about, but this is a shorter way to do it. So inside of for, instead of the three little mini statements, you essentially just declare whatever the individual value will be.

[00:13:13]
So we could say int value:, and then you give it the array name, so array. So what this does is says, take the element, whatever element we're on from array, that will be like index 0 at first, assign it to this variable called int value. Do whatever you wanna do, come back to the loop, it'll do the second value in array, put that into value, third, fourth, fifth, whatever, all right?

[00:13:50]
So, I'm gonna say, if the value equals, we used that double equal sign, look at this, numberTosearchFor, return true.
>> Angie Jones: Do I do a else return false right here, anyone? Why wouldn't I do that?
>> Audience: Because we wanna keep going through our for loop.
>> Angie Jones: I wanna keep going through the for loops, so be very careful when you're inside of loops.

[00:14:29]
If I return outside of that loop, that's it, it won't check the rest. So this would check the very first element, say that's not equal, no, it's not in there, [LAUGH]. But it didn't look all the way through, so we got to just kind of let it go.

[00:14:43]
If it does happen to find it, cool, break, no need to look through the rest of the elements of the array. But if not, all right. Finish going through all of them once you are done. If I get to this point and I have not already returned true, it's safe to go ahead and return false.

[00:15:01]
Because if it was there, I would have already left this method anyway, all right? So that's our search, so back to our while condition. We're gonna say while(search(, and we'll give it our array which was called ticket and the number that we wanna search for. I guess we can assign this to a random number.

[00:15:27]
And we'll say random number.
>> Angie Jones: Okay.
>> Angie Jones: So, if we get outside of this loop, that means the number is unique, right? Otherwise if it generates the same number and this was equal to true, it will go again, generate another number until that is false. Once it's false, we come outside of that, and now it safe to add it to the ticket.

[00:16:01]
We got our numbers, now, we wanna go ahead and print them, okay? So back to our main method, we're going to print the ticket. So we'll call a method call, print ticket, we'll pass in the array. We haven't written print tickets yet, so let's go ahead and do that.

[00:16:23]
Y'all got this much?
>> Audience: So I have a question?
>> Angie Jones: Sure.
>> Audience: On line number 16 we already defined that that max array for the ticket is LENGTH, we defined that with that constant. So couldn't you have done enhanced for loop on line 19 as well? Cuz you already said what the length was for the array?

[00:16:40]
>> Angie Jones: Except I don't have anything. I'm glad you asked that, I meant to point this out. I don't have anything inside the array yet, right? So it only makes sense to use the enhanced for loop when you actually have values inside, because I'm actually assigning it to a variable.

[00:16:56]
So on the first run, this equals nothing, right? Nothing is inside of there, so it wouldn't really make sense to do an enhanced for loop here.
>> Angie Jones: And I need this incrementer, cuz I'm using it on 26 to actually set a value. So this i is important right here.

[00:17:22]
>> Angie Jones: All right, so print ticket, let's go ahead and write a method to print ticket. So this one will be public static void printTicket. It takes an array of integers.
>> Angie Jones: And now, I want to sort the array so that all of the numbers are in order, right?

[00:17:51]
So when you get your lottery ticket, you have the numbers in, what's that, ascending order? So I wanna have that for my beautiful lottery ticket, there are convenience methods. So if you use the Arrays class, this is where static comes in again. I don't want to instantiate the Arrays class and all of that, I can just say Arrays., and they have a list of these static methods for me to use.

[00:18:19]
So I don't have to create a new Arrays object and all of that stuff. They don't need any data from me other than the array, I pass that in, and we're good to go. So notice all of these nice convenience methods, they can do a binary search on the array.

[00:18:36]
So when people ask you in your interviews, how would you do a binary search? Arrays.binarySearch, [LAUGH] that usually doesn't go over well, don't do that. [LAUGH] But you can compare, you can do all sorts of things, one of which is sort. So I can sort this array. Arrays does need to be imported.

[00:19:00]
And then I just pass it the array, and now this will be in ascending order for me, all right? Now I want to print the tickets. Again, in order to print, I'm gonna need a loop, right? So I'm gonna have to go and basically go through each element of the array, print them all out.

[00:19:21]
Because the array is populated, I can use the enhanced for loop. If you don't wanna use it, you're not comfortable with it, you just don't want to, you can always use the other regular for loop as well, okay? So which one y'all wanna use?
>> Audience: Enhanced.
>> Angie Jones: All right.

[00:19:39]
Okay, so we'll say int value, I'll just call it number, int number, and then array. And this time, I'm not gonna println, so println prints a new line with a line break. I want all of the numbers to be on the same line. So I'm just going to print, print stays on the same line.

[00:20:06]
So I wanna say print, man, you might need the other array. Let me see, cuz I need the index, well, I don't, actually, since I have the value, I could just do that.
>> Angie Jones: Okay, I can just do this. I thought I needed to do the index, ticket[i], right?

[00:20:28]
But that's what's stored inside of number, whatever ticket[i] was. So I can just say number, and then I'll put a little something in between them, so the numbers aren't all jumbled together. Let's just do a space and a pipe, for example, okay, so I think that should work.

[00:20:49]
>> Audience: What is the pipe doing there?
>> Angie Jones: It's just gonna put a pipe in between the numbers so that they aren't all just boom, boom, boom, and one big ugly-
>> Audience: Okay, so it's not the logical operator pipe, it's just a character, okay.
>> Angie Jones: No, it's a piece of text.

[00:21:06]
All right, so I think that's our lottery ticket, wanna run it, all right.
>> Angie Jones: All right, and there I have it, 7, 17, 44, 55, 56, and 68, six random numbers printed in ascending order, that was fun.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now