Lesson 6 - If Statements, Conditionals, and Loops
A conditional statement is a statement in Java that will execute directions differently depending on the whether another statement of code is true or not. For example, you may want to go to a specific webpage if a user clicks on a specific link, or display a message if a user inputs an incorrect password. These scenarios are dependent on how the user interacts with our program.
Before we can dive into learning about conditionals, we need to first be able to gain and store user input as data in our program. Let's do this below:*****
First, we are going to need to use the Scanner
class and create a new instance scanner
. We also need to assign a value to scanner
to link the scanner to the InputStream window. You will not understand this now, so just follow this generic code block to achieve this.
import java.util.Scanner;
public class ConditionalStatements {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
}
}
You may want to name your input scanner something different depending on the situation in which you're requesting information, but this will do for now.
Let's set up the program to acquire an integer value from the user. To do so, we need to use the following statement:
int userInput = scanner.nextInt();
On the right of the statement, the data type scanner.nextInt( )
will return an integer based on the input from the scanner
object. On the left of the statement, the int
that is returned by the scanner will be stored as an int
variable with the name userInput. I will also clean this up and enter a prompt statement before the scanner
asks for the user's input and a print statement of the value entered by the user.
Our full text block is as such:
import java.util.Scanner;
public class ConditionalStatements{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer value: );
int userInput = scanner.nextInt();
System.out.println(userInput);
}
}
It is important to understand that if we are to provide the program with anything other than an integer value, the program will return an error. There is error handling that can be placed to avoid such an issue. However, we will not go into this until later.
Conditionals, If Statements
Now, let's start thinking about if statements.
We can compare our user data using a set of instructions known to programmers as if
statements. There are also if else
statements in Java that we will go over a bit later.
It is important to recognize the logic of computers. The computer understands information in a binary context. This means that it uses what we can call boolean
logic. Boolean
is essentially the comparison to what is true and what is not true. An if
statement and, later, case
statements and loops
rely on this boolean
logic to function.
Let's introduce a new type of variable. The boolean
variable. A boolean
is a primitive data type and can only be assigned two values: true
or false
.
Consider the following statement:
If Mark eats at least five of his veggie, then he can have dessert.
At face value, this statement has one meaning. If Mark eats at least five of his veggies, then dessert is his to take. However, there is one more statement that is here but is not explicitly stated. If Mark doesn't eat at least five of his veggies, then he does not have dessert. What happens then? Does Mark have another option for not eating veggies, such as eating a fruit instead? Or instead of having dessert, maybe Mark will have to spend 30 minutes running.
Now, why did I go through all of these seemingly random scenarios about Mark and his veggies? Well, we can do the same in our Java program.
Say we have a set of instructions for a user to log in to a secured account on a webpage. Consider the following:
If Mark inputs his account password correctly, then he will gain access to his account. If Mark does not input his account password correctly, then an error message will display saying "Password incorrect. Please try again." Perhaps there is an instance where Mark inputs his password incorrectly 3 times, then his account is locked.
This scenario is possible using if
statements. The syntax for an if
statement is as follows:
if(x > 10){
some instruction here;
}
Notice, the if( )
function holds a statement inside. This might look familiar from high school algebra as an inequality statement. This is boolean
value that our program is going to compare the input value to in order to run this instruction. Notice, if x is greater than 10, then the instruction between the curly braces will run. If x is less than 10, or perhaps equal to 10, then nothing involving the instruction here will run. Either the code will continue to run after the if
statement, or the program will stop depending on the instruction.
Now, you can have multiple if
statements. You would repeat the process to achieve this.
if(x>10){
some instruction here;
}
if (x<10){
some other instruction here;
}
You can also opt for an easier route when executing only two if
statements using an if-else
statement. Essential, this says that if a statement is true, then this will happen. Else, this will happen instead. The structure is similar:
if(x>10){
some instruction here;
}
else{
some other instruction here;
}
Notice that the else
statement does not contain an argument. This is because the input will only compare to the argument in the if
statement. If the if
statement returns false, then it will automatically run instructions in the else
statement.
Before we move into code, let's talk about some boolean logic terms that are useful:
Phrase | Java Code | |
---|---|---|
not | ! |
|
and | && |
|
or | | | | |
true | true |
!false |
false | false |
!true |
greater than | > |
|
greater than or equal to | <= |
|
less than | < |
|
less than or equal to | <= |
|
equal to | = |
|
not equal to | != |
|
equivalent (boolean logic for string values) |
== |
This information is important for comparing statements in ways that Java will understand.
Let's take a look at a simple example below:
import java.util.Scanner;
public class ConditionalStatements{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Select an integer: );
int userValue = scanner.nextInt();
if(userValue > 5){
System.out.println("There are at least 5 chickens in the barn.");
}
else{
System.out.println("There are less than 5 chickens in the barn.");
}
}
}
Output will be dependent on the user's selection. But notice, if the user enters a value greater than 5, then the statement "There are at least 5 chickens in the barn." Any other value 5 or lower will return the other statement. Now, let's think of this in the context of the Mark and his veggies problem. Remember, he has to eat at least five.
public class ConditionalStatements{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("How many veggies has Mark eaten?: );
int userValue = scanner.nextInt();
if(userValue >= 5){
System.out.println("Mark can have dessert.");
}
else{
System.out.println("Mark cannot have dessert.");
}
}
}
Recall that we discussed a possible alternative for Mark obtaining dessert. Perhaps Mark can eat a fruit instead. We can compare multiple boolean statements at once using the and operator &&
or the or operator | |.
Suppose that Mark must eat at least 5 veggies or one fruit. We'll have to take multiple inputs from the user:
public class ConditionalStatements{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("How many veggies has Mark eaten?: ");
int userVeggies = scanner.nextInt();
System.out.println("How many fruits has Mark eaten?: ");
int userFruits = scanner.nextInt();
if(userVeggies >= 5 || userFruits >= 1 ){
System.out.println("Mark can have dessert.");
}
else{
System.out.println("Mark cannot have dessert.");
}
}
}
Suppose that Mark must eat both 5 veggies and one fruit:
public class ConditionalStatements{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("How many veggies has Mark eaten?: ");
int userVeggies = scanner.nextInt();
System.out.println("How many fruits has Mark eaten?: ");
int userFruits = scanner.nextInt();
if(userVeggies >= 5 && userFruits >= 1 ){
System.out.println("Mark can have dessert.");
}
else{
System.out.println("Mark cannot have dessert.");
}
}
}
You can also nest if
statements, meaning that you can have an if
statement inside of another if
statement. The first if
statement will have to be true before any subsequent if
statements will run.
Suppose that if Mark eats at least five veggies, and then if Mark does his homework, then he can play outside. Notice the nesting of the if
statements. The second set of if
cannot happen if Mark eats less than five veggies. Let's see how this would play out:
public class ConditionalStatements{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("How many veggies has Mark eaten?: ");
int userVeggies = scanner.nextInt();
if(userVeggies >= 5){
System.out.println("Did Mark do his homework? Enter 1 for yes or 2 for no: ");
int userHomework = scanner.nextInt();
if(userHomework = 1){
System.out.println("Mark can play outside.");
}
if(userHomework = 2){
System.out.println("Mark cannot play outside.");
}
}
}
Here, the only options for the if
statements are 1 or 2, for yes or no, to Mark having done his homework. See what happens when you type an integer other than 1 or 2.
Now, all of this has been quite a lot to digest. But understand that it's incredibly powerful to have many options for running code that give flexibility and diversity to what your program can do based on the information that it takes in.
Next, we're going to look at an easier way to run code that might have many different scenarios that would make if
statements more complicated and tedious and confusing to read.
Switch, Case and Break Statements
When we have different lines or blocks of code depending on the value of an individual variable, the switch
statement instead provides a more reader-friendly option.
The switch
block is similar to if
block. However, rather than using if, we use case. See below:
public class Switch {
public static void main(String[] args){
int x = 7;
switch(x)
{
case 1:
System.out.println("Red");
break;
case 2:
System.out.println("Blue");
break;
case 3:
System.out.println("Green");
break;
default:
System.out.println("None");
}
}
}
There are a few of fundamental differences that I'd like to point out. Above, we have the same structure as if
blocks. We have an instantiation of the variable x, x = 7
, then we have an activation of the switch
method, switch(x)
. Notice that in order to activate the switch
, we need to input the variable that we are running our boolean
comparison through. In this case, variable x
.
Now, each case
has a different block of code that will run if the boolean runs true. The value of the variable x
will be compared to each case and run that case. In this case, the variable is equivalent to 7. This is not equal to any case number that we have in the above code block. What happens in this case?
Well, similar to an if-else
statement, the default
case will run here, printing the line "None."
While and Do-While Loops
While
and do-while
loops build on our knowledge of if
blocks. Say that we want to run a block of code for an extended period of time while a user makes certain selections. We can do so using a while
loop. Let's play a game.
We want our user to pick a number between 1 and 10 and we want to the program to randomly generate this number each time the user starts the game. We also would like for our program to tell us if they are guessing too high or too low compared to the generated number each time they guess. If the player guesses the number correctly, the system will let the user know.
First, let's think about how many statements that we'd like to have based on the requested information above. We will need an if
statement if the player guesses higher than the generated number. We will need another if the player guess lower than the generated number.
Normally, you might think that we will need an else
statement to alert the user that they guessed the correct number. In this case, the while
loop is going to do that step for us, because while the user is guessing the correct number, the while
loop will continuously run this code for us until the user is able to step out of the loop. So rather than use an else
statement for correctly guessing a number, I'm going to use it for error handling, which we haven't discussed much this far.
I want to stress that there is some code in here that you will not understand quite yet and that's okay. I promise we are getting close to discussing the class
topic.
I will say that we are calling upon the built-in Random class
that Java provides for us. We are instantiating an int
variable named randomNumber and asking Java to return an int
between 0 and 10. This is similar to how we call a Scanner
object when asking for user input, which I have also done below.
Take a look at this code block:
java.util.Random;
java.util.Scanner;
public class NumberGame{
public static void main(String[] args()){
Random randomNumber = new Random();
int randomNumber = rand.nextInt(10);
Scanner scanner = new Scanner();
System.out.println("Guess a number between 0 and 10!");
int userGuess = scanner.nextInt();
while(userGuess != randomNumber){
if(userGuess > randomNumber){
System.out.println("Number guess is too high. Try again");
}
}
}
}
For Loops
Next Lesson: Lesson 6a - Project 2 - Menu Selection with User Input
Table of Contents: Table of Contents