Today I will write about conditional branching.
Performs processing when the conditions are met and when the conditions are not met The code
The most basic conditional branching expression
The basic form is like this.
Set a conditional expression (a = 1, a> 2, etc.) in if () If it is established, the processing in the first {} is performed. If it is not established, the processing inside {} after else is performed.
if statement basic syntax
if(conditions){
//Processing when the conditions are met
}else{
//Processing when the conditions are not met
}
Click here for example sentences Because number is set to 1 Correct answer and output When a case other than 1 is set Incorrect answer Furthermore, it is output as an incorrect answer.
if statement
public class Main {
public static void main(String[] args) {
int number = 1;
if(number == 1){
System.out.println("Correct answer");
}else{
System.out.println("Incorrect answer");
System.out.println("Further incorrect answer");
}
}
}
If you want to make a finer conditional branch, write an else if statement in between.
Condition 1 if () Let else if () be condition 2. If you continue to write else if () Condition 3 Same as above Condition 4 You can increase it.
if statement basic syntax
if(Condition 1){
//Processing when condition 1 is met
}else if(Condition 2){
//Processing when condition 2 is met
}else{
//Condition 1,2 Processing when neither matches
}
Click here for example sentences Because number is set to 1 Like! And output If number is set to 2 ❓ and output When a case other than 1 is set It will be output clearly.
if statement
public class Main {
public static void main(String[] args) {
int number = 1;
if (number == 1) {
System.out.println("Love!"); //Processing when condition 1 is satisfied
}else if(number ==2){
System.out.println("❓") ; //Processing when condition 2 is satisfied
}else {
System.out.println("I hate you"); //Processing when the conditional expression is not satisfied
}
}
}
The word condition is coming up. I will introduce the processing when dealing with numerical values in that.
Roughly speaking, write as below. Same with == ! = Other than that It should be noted that there are many unusual shapes.
Comparison operator
if(Example==1)//If equal
if(Example>1)//If it exceeds 1
if(Example>=1)//If 1 or more
if(Example!=1)//If other than 1
I made a list, so please have a look for reference.
Comparison operator | When the conditions are met |
---|---|
a==b | equal to a and b |
a>b | When a exceeds b |
a<b | If a is less than b |
a>=b | When a is greater than or equal to b |
a<=b | When a is less than or equal to b |
a!=b | When a is other than b |
Recommended Posts