Greetings! Today's article we will dive into Java statements, in particular, the if-else statement. We will also introduce the Scanner class (for user input) as well! Are you ready!?!??!?! Let's have some Java!
- Here we have the Scanner class. This class allows us to have user input so users can interact with our code. You will notice the new Scanner object with a variable name of 'scanner' (how convenient lol). Also, we need in parenthesis(System.in) to allow for input from an outside source(think keyboard).
- Next, we are simply printing out our question posed to the user.
- On line 3, we create a String 'day' to take in the user's input (scanner.NextLine()).
- Now, on line 4, the fun starts!!! Our if statement starts off with variable 'day' followed by the method 'equalsIgnoreCase'. This method allows the user to enter in small or LARGE caps (lol). We then have our day 'Monday', where if the user types it, the code will print the result.
- On line 5, we have an else-if statement that allows for another choice for the user to type in. It also has its own output.
- On line 6, we 'end' our if-else statement chain with the last printout should the user choose any other day besides Monday or Saturday.
- Next, we have to always 'close' our scanner so it knows that our user input has come to an end.
- In green, we can see the user's answer after the question prompt.
- Finally, we see the result of the user's selection. Whew!!! LOL!!!
We did it! We went through Java's if-else statement and it's Scanner class!! Now, we definitely need some Java to drink up after this exercise. I hope you learned something new today, thank you for taking the time to go through this article, and as always, stay Java!!!
Cloud Engineering Is Your Next Career.
1 年Nice I will check it out!!