3.1 Iteration minilab
boolean condition = true;
if (condition) {
System.out.println("Condition is true");
}
- if-else: runs code if a condition is true, but if not, it will run different code
boolean condition = false;
if (condition) {
System.out.println("Condition is true");
} else {
System.out.println("Condition is not true");
}
- if-elseif-else: runs code if a condition is true, if not it does something else. Checks another condition if it were true, and again does something different if it is not.
boolean conditionA = true;
boolean conditionB = false;
if (conditionA) {
System.out.println("Condition A is true");
} else {
System.out.println("Condition A is not true");
} if (conditionB) {
System.out.println("Condition B is true");
} else {
System.out.println("Condition B is not true");
}
int val = 3; // declares the value
if (val == 0) { // checks if value is 0
System.out.println("Val: 0"); // prints value is 0 if it is true
} else if (val == 1) { // if not check if value is 1
System.out.println("Val: 1"); // prints value is 1 if it is true
} else if (val == 2) { // if not check if value is 2
System.out.println("Val: 2"); // etc
} else if (val == 3) { // etc
System.out.println("Val: 3");
} else if (val == 4) {
System.out.println("Val: 4");
}
int val = 3; // declares the value
switch (val) { // declares the switch-case and the variable being tested is 'val'
case 0: // if val is 0...
System.out.println("Val: 0"); // print "Val: 0"
break; // leaves the code block (same thing a closing curly bracket does)
case 1: // if val is 1...
System.out.println("Val: 1"); // print "Val: 1"
break; // leaves the code block
case 2:
System.out.println("Val: 2");
break;
case 3:
System.out.println("Val: 3");
break;
case 4:
System.out.println("Val: 4");
break;
}
boolean a = true;
boolean b = false;
if (a || b) { // function 1
System.out.println("function 1 passed");
} if (!(!a && !b)) { // De Morgan function 1
System.out.println("De Morgan function 1 passed");
}
boolean a = true;
boolean b = false;
if (!(a && b) || (b || b)) { // function 2
System.out.println("function 2 passed");
} if (!(!(!a || !b) && (!b && !b))) { // De Morgan function 2
System.out.println("De Morgan function 2 passed");
}