If and Else Statements
Lesson on if and else statements
- What is if and else condition
- If and Else if condition
- Last if/else statement
- Switch Statement
- De Morgan's law
if(condition) {
// code block for if condition is true
} else {
// code block for if condition is not true
}
if (condition) {
// code block 1 for if condition is true
} else if(condition2) {
// checks if condition 2 is true and runs this code block
}
if (condition) {
// code block 1
} else if (condition2) {
// code block 2
} else {
// last code block where neither condition or condition2 are true
}
import java.util.Scanner;
public class ConditionStatements {
public void go() {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
if (num == 1) {
System.out.println("Number 1 was selected");
} else if (num == 2) {
System.out.println("Number 2 was selected");
} else if (num ==3) {
System.out.println("Number 3 was selected");
} else if (num ==4) {
System.out.println("Number 4 was selected");
} else if (num ==5) {
System.out.println("Number 5 was selected");
} else {
System.out.println("Number was not 1-5");
}
}
public static void main(String[] args) {
ConditionStatements cond = new ConditionStatements();
cond.go();
}
}
ConditionStatements.main(null);
import java.util.Scanner;
public class SwitchStatement {
public void go() {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
switch (num){
case 1:
System.out.println("Number 1 was selected");
break;
case 2:
System.out.println("Number 2 was selected");
break;
case 3:
System.out.println("Number 3 was selected");
break;
case 4:
System.out.println("Number 4 was selected");
break;
case 5:
System.out.println("Number 5 was selected");
break;
default:
System.out.println("Number was not 1-5");
}
}
public static void main(String[] args) {
SwitchStatement cond = new SwitchStatement();
cond.go();
}
}
SwitchStatement.main(null);
if (!((true == true) && (true == false))) {
System.out.println("De Morgans law is true");
}