Summary of control syntax to implement these
ʻif (! flag)
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
var i = 10;
if (i == 10) {
System.out.println("The variable i is 10.");
} else {
System.out.println("The variable i is not 10.");
//Same as below
//System.out.println((i==10)?"Variable is 10":"Not 10");
}
}
}
public static void main(String[] args) {
var i = 100;
if (i > 50) {
System.out.println("The variable i is greater than 50.");
} else if (i > 30) {
System.out.println("The variable i is greater than 30 and less than or equal to 50.");
} else {
System.out.println("The variable i is 30 or less.");
}
}
public static void main(String[] args) {
var rank = "Instep";
switch (rank) {
case "Instep":
System.out.println("It's very good.");
break;
case "B":
System.out.println("Is good.");
break;
case "Hinoe":
System.out.println("Let's do our best.");
break;
default:
System.out.println("???");
break;
}
}
//Arrange multiple cases in fallthrough or implement conditions
public static void main(String[] args) {
var drink = "beer";
switch (drink) {
case "Sake":
case "beer":
case "wine":
System.out.println("It is brewed sake.");
break;
case "Brandy":
case "whisky":
System.out.println("It is distilled liquor.");
break;
}
}
public class Main {
public static void main(String[] args) throws Exception {
var i = 1;
do {
System.out.println(i + "This is the second loop.");
i++;
} while (i < 6);
}
}
//NG example: Floating point type for counter variable
public class Main {
public static void main(String[] args) throws Exception {
for (var i = 0.1f; i <= 1.0; i += 0.1f) {
System.out.println(i);
//0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.70000005, 0.8000001, 0.9000001
}
}
}
//Sequential operator
public static void main(String[] args) {
for (var i = 1; i < 6; System.out.println(i + "This is the second loop."), i++);
}
public class Main {
public static void main(String[] args) {
var data = new String[] { "neko", "tama", "mike" };
//Extended for instruction
for (var value : data) {
System.out.println(value);
}
}
}
//Example of receiving command line arguments with args and outputting them in order with extended for
public static void main(String[] args) {
for (var value : args) {
System.out.println("Hello," + value + "Mr.!");
}
}
break label name;
//Exit from the specified loop
public class Main {
public static void main(String[] args) {
limit:
for (var i = 1; i < 10; i++) {
for (var j = 1; j < 10; j++) {
var result = i * j;
if (result > 50) {
break limit;
}
System.out.printf(" %2d", result);
}
System.out.println();
}
}
}
Recommended Posts