Java Lesson 10 | The Switch Statement
Big Mac heads!
- Today I'm going to be talking about the switch statement in Java. I know I should have covered this before. I probably should have covered this after the if statements or the loops or something like that tutorial, but I forgot, so my bad. I'm going to teach it now.
So the program we're going to be making here is that it asks what place they finished in, like a race, and they enter the place number, and it tells them what their prize is. So, um, I'm just gonna, you know, give the prompt: "What place did you finish?" Oh, and you know, create—we're going to be getting some input, so just create that Scanner object.
We're going to have an integer that we're going to be testing. I'll call that place = scan.nextInt().
Alright, so now here's the switch statement. What we do is we're going to be testing the place variable. So we do switch and in parenthesis place.
Then we type case, and I'll type 1, and then a colon. This means if place is equal to 1, do this. So if case is equal to one, then System.out.println("You won a hundred dollars!" or "Yeah, you won 100 dollars.")
Alright, and then at the end, we have to do this break statement, just "break;" semicolon, which means, um, don't look for any more cases. We found it, break out of this switch statement.
So if it is equal to one, then it breaks. Now case 2, which means if this variable we're switching on case—actually, no, it's still within here. Sorry, just after the break statement—if place is equal to 2, then System.out.println("You won fifty dollars!") and break.
And case 3, so if they came in third, System.out.println("You won twenty-five dollars!") and break.
Then here's the last part: default. You don't need to put a break statement for default because what default means is that—so just how to not enough curly braces on default means at the end none of these cases were true, so do this, because none of them were true.
So, like, if they entered "4," something—no prize.
Alright, so what this did is we—whatever the input became place—and we switched it. So if place is one, the case, one: "You won a hundred dollars!" Break it. That's true—no need to go through all this. We found it.
But if it's not true, it'll go to case 2, and if that's true, it'll break. If not, it'll do this and break. If not, it'll just do this, and we can break. We won't get an error or anything, but it's just unnecessary because it'll stop after this one anyway.
So I'm just going to run this, and I'll say, "What place did you finish?"
"Three!"
"You won $25."
"Um, I won first!"
"You won a hundred dollars."
"And I came in, like, 17th."
"No prize."
Um, yeah, and you can see how that would save you a lot of code if you were trying to do this with if statements.
So that's the switch case statement for you, and see you next time!