The course is part of this learning path
This course explores the fundamental concepts and syntax associated with Control Flow and showcases these with some real-life projects.
Learning Objectives
- Learn about the three categories of control statements: sequential, selection, and repetition
- Manipulate control statements using the continue and break statements
- Learn about pseudo-random numbers and the Random class
Intended Audience
- Beginner coders or anyone new to Java
- Experienced Java programmers who want to maintain their Java knowledge
- Developers looking to upskill for a project or career change
- College students and anyone else studying Java
Prerequisites
This is a beginner-level course and can be taken by anyone with an interest in learning about Java.
In the previous lecture, we overviewed the three primary categories of control statements: sequence or sequential, selection, and repetition. In this lecture, we will look more deeply into selection control statements which is one of the categories of control statements. I'm quite certain, I drive my face-to-face students a little crazy with memorizing and practicing terminology and skills but many of them have contacted me later on and told me they got jobs because they were able to better articulate how different programming constructs work and what they're for. So, it is crucial to be able to communicate and discuss programming as well as being able to create practical code.
Back to selection control statements. In Java, there are three syntactic varieties of control statements, specifically selection control statements; which are the if statement, the if else statement, and the switch statement. The first of the selection control statements, the if statement, applies to a block of code and either executes that block of code or skips over the block of code, depending on a condition. The condition must resolve to a Boolean value.
So, it could be a value, a variable, a relational operation, a logical operation or anything that ultimately has a Boolean value, that is true or false. Let's create a file called SelectionFun, 'Source', 'New',' Java', 'SelectionFun'. All right, so let's fill in public static void main(String[ ] args) There we go. Similar to our earlier examples, we're going to use an integer named age to make a decision. This time, we will in sequence say welcome to the Pub and Grille. And then ask the user their age. All right, so let's create the age variable, and then we're going to say, to the Pub and Grille and then we're going to ask for the age. So, in order to do that we need the scanner for user input and notice it's red here. I can hit all Enter on the keyboard, and it will import this for me or I could have typed it out myself. There we go. There's scanner. And now we're going to say "Please enter your age", and I could use print with a tab but I'm using print line here so it's no big deal, keyboard.nextInt(). Perfect. Now, we will test and see if the user is 21 or older. 21 is the legal drinking age in the United States.
So, we will offer the user a beer if they are 21 or over. If age is greater than or equal to 21 because it's 21 or over, you have to pay very close attention to those details. Okay, you'll notice that the curly brace shows up automatically, and we will offer them a beer. So, system.outprintIn("Here, have a beer.") All right, so it's conditional. Now sequentially, outside of the if statement block of code, we will then tell the user thanks for coming to the Pub and Grille. So, I'm going to write code after this if statement, println, "Thanks for coming to the Pub and Grille." All right. Now, let's run the code a couple of times and test it with some different values. So, we've got the the SelectionFun here. I'm going to run it and we will see what we can do here. Got that please into your age. Let's try it with 16. It says, "Thanks for coming to the Pub and Grille." It does not offer me a beer. And I can run it again, and let's say the age is 21 exactly. Here have a beer. Okay, good, and what about 25 we'll say. Here, have a beer again, right? Because it's 21 or over. Pretty cool.
Our code is getting smarter. It's either offering a beer or not depending on the user's age. So, that's the if statement. But let's improve our communication, in this case an if else statement. So in the if statement, single selection control statement meaning that it either does something or doesn't based on condition. With the if else statement, you can do one thing or another based on the condition. Thus, if else is considered a double selection control statement, but you can also change them to which we'll find out. So, let's change our code to now offer the user a coke if they're under 21. So, that's the only other possibility if they're not 21 or over. They're obviously this means otherwise, else we're going to offer them a coke. "Here have a coke." Right? There we go. Now, let's run it again with the different ages and see what happens. So run selection control right there. please into your age, 16, "Here have a coke," Right? Because it went here. This is false because 16 is not greater than or equal to 21. It went down here, and then it printed out, "Here have a coke." Now let's try 21, right here. "Here have a beer." And of course 25 again "Here have a beer." Pretty cool, huh? Now, what if we want to tell our users something more specific? If they're say 16 or older, but not quite 21 yet. So we can chain if else statements to simulate more than just double selection. That is, to simulate multiple selection or multi-way selection. So, let's modify our code to offer them a coke and say, "At least you can drive", if they're 16 or higher. So, what I'll do here is between these two, I'll say else if age equals greater than or equal to 21, I will say system.out.println() Here, have a coke. And also I will say, "At least you can drive." Right?
So, what will happen is if this one is false, it will check this one. And then if this one is accurate, it will do that. And then skip it. If this one is true, they will skip that. And then if neither of these are true, it will default again to the else statement. So, let's try this again. Right click. I'm going to run selection. Let's try it with some smaller number. All right here, 4, oops. 147, I guess they get a beer, right? If you live that long you deserve a beer. Now, here's a 14. It says, "Here have a coke." So, that's our default because it's under the 16 that we were working with. Let's try 16 on the dot here. "Here have a coke. At least you can drive." Right? And of course it says, "Thanks for coming." That's outside of the selection control. And then we're going to right click it again and then test this again. Please enter your age. Let's try 18. "Here have a coke. At least you can drive." And once again we will try maybe 21 "Here have a beer." Good.
So, now we have multiple possibilities. The if and if else are both very useful for different circumstances. And we have seen that we can simulate multi-way selection if we chain if else statements. But there's a third selection control statement available in Java called the switch statement. This one is not as flexible but naturally provides multi-way selection. Let's create a new file named GradeFun. So, let me right click this new, Java class, GradeFun. And let's give this a public static void main(String[ ] args). There we go. Put in main this time. So, we're going to ask the user to enter a character A char. And for each grade we will tell them how they're doing in class. Note that in some countries like for the British and Canadian friends, the term mark is used commonly instead of grade. But here in the United States, we often use the term grade or letter grade. We're only going to allow the upper case A, B, C, D, and F. If they enter anything else, we will tell them it is an invalid grade. So, let's write some code here. We will need a scanner, system.in Right here, same thing again. You'll notice it even tells you what to do or tells you what's going on. So, if you hover over, it will say press Alt + Enter or you can just click import class, same thing. Very good. And let's see here we need a character which we call grade and we need to get the input.
Of course, we need to say system.out.println("Enter a grade"). So, this will get the letter grade, grade = keyboard.next(). There we go. And now we'll have the switch statement. So, you know what next returns a string. So, we have a couple options here. We could change this to a string, that will still work. But I think what I'm going to do is I'm going to use the string method called charAt() and just follow along for now. This will be a string. But since there's only going to be one char, we're interested in the first one, we will get the character at 0, which is the first character. So, we should be okay now. Okay, so let's write the actual switch statement right here, switch(grade). And I'm going to write that just to keep me organized. And if the case is that the character is a capital A, then what we're gonna do is we're going to print out, "Great job." And you have to put a break statement here after you're done with each case. It should put this in the right location, there we go.
For a B, we will say, "Good job." Not quite as enthusiastic. "You can do better." case D : "You're getting pretty close to failing." Case F is, "You are failing the course!" With enthusiasm, of course. And then the default statement is kind of like an else. It's what happens if none of the others are true. So, this one's going say, "You have entered an invalid grade." Okay. So, in context to switch statements, the break statements are actually crucial. So, otherwise each one of these cases would perform what's called fall through. They automatically execute everything until they reach the end or reach a break statement. The default does not require a break statement since it's the last statement. Now, let's run it and try different letter options. Okay, so we're going to run GradeFun here. Enter a grade, we'll put an A. It will say great job, so far so good. Run. And we'll try it with B, "Good job".
So, that's working. Since this has a minimal number of cases here, it's pretty easy to test. So, you can do better with the C. We will do a D. You're getting close to failing. We will also do F. You're failing the course. And of course we have to try something invalid just to make sure the default's working. So, let's put Q. You have entered an invalid grade. So, what happens if we use lower case letters? So, let me see here. If we do a lower case a, it will say It's an invalid grade. So, our program considers lower case even if they're valid technically letter grades to be invalid. One way to handle this is to use fall through that I mentioned just a little bit ago to our advantage. So, we're going to modify these to work with lower case as well. So, I'm actually going to put this immediately below the upper case, and the same thing here for b, and then the same thing here for c. Same thing here for d, right there. And then same thing here for f. We're going to run that. And let's try it with a couple of different things here. A still works.
We're going to try it with a, still works. Great job. So, it's improved. Let's do some of the borders here. So, D still works. And then d still works. The same thing, it actually works properly this time. And then we want to try something with like an upper case, something like that. There you go, you've entered an invalid grade, excellent. Now, I have a little challenge for you. I'd like you to create a new Java file called Fraternity. In the program, prompt the user for their age and their gender. Use selection control statements if, if else, or switch, and tell the user that they are eligible to join the Fraternity if they are male using a gender value of M or F and if they are 19 or over for their age.
So, the big hints would be: use relational operators and logical operators. And also you might want to pay attention to how I grabbed the single character too, but you can also use just a string. So, pause the video and try out this challenge for yourself. Come back when you're done or if you need some help. How did that go for you? Did you complete this challenge? Let's do it together and see what code we can write to solve the challenge. Also, you may not have done exactly what I'm about to do, but that's usually okay. The more complex these challenges and projects get, the more likely it is that there will be differences between our code. So, let's create our Fraternity file. Fraternity, and we're going to do system. Oops, sorry.
I guess we need public static void main first, right. Don't get ahead of ourselves, there we go. There's the end of main. And we of course need to grab some sort of inputs. So, we're going to need a scanner. Okay. And import the scanner, good. Now, we need one for age and then one for gender. Awesome. So, if the user enters an age that is greater than or equal to 19, and the gender is male, then they get to join the fraternity. Otherwise, we have to tell them they can't join the fraternity. Okay, so let's prompt them here. This one I'm going to use just print and say, "Enter your age." And I may both put a tab there and we need to age = keyboard.nextInt. Here we go. And then system.out.print, "Enter your gender/t". And we're going to say gender equals using our little trick technique there.
Next grabs only a full string up to the next space and then we have to treat it like a character using the charAt. So, let's do this. keyboard.next() and then .charAt(0). There we go. That will grab the gender. if(age >=19 && gender == 'M') We could set it so that it works with m too but I think we're good for now. That's the end of if-else, if they don't qualify then we have to tell them that, "you cannot join the fraternity. And then we will say, You can join the fraternity. Okay. All right. So, let's run this. And so, we've got age right here. We'll try 18 and then M for male. Sorry, you can't join the fraternity even though they are male, they're not 19 or over. So, this one requires 19 or over. Let's run it again. We'll say 22, which is a good age but then say female, so F. Sorry, they can't join the fraternity. Age requirement is met, gender requirement is not. So, now let's try 20 and male. You can join the fraternity. So, notice that the user can only join the fraternity if they are both 19 or older and also male.
If they're female but meet the age requirement or their male and do not meet the age requirement, they can't join. Excellent work. You now have some stronger foundation for the selection control statements if, if-else, and switch. Before we move on to the next lecture, can you remember all three categories of control statements? That's it. Sequential or sequence, selection, and repetition. We discussed sequential as the default control statement. We just got down discussing selection in this lecture. In the next lecture, we'll look at how to make our programs repeat some tasks multiple times as necessary. I'll see you there.
John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.