public class Main { public static void main(String[] args) { System.out.print("A,"); System.out.print("B,"); System.out.print("C."); System.out.println(); System.out.println("END"); } } A,B,C. END
public class Main { public static void main(String[] args) { double d = 3.1415926; System.out.printf("%.2f\n", d); // 显示两位小数3.14 System.out.printf("%.4f\n", d); // 显示4位小数3.1416 } }
public class Main { public static void main(String[] args) { int option = 1; switch (option) { case 1: System.out.println("Selected 1"); break; case 2: System.out.println("Selected 2"); break; case 3: System.out.println("Selected 3"); break; } } } Selected 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public class Main { public static void main(String[] args) { int option = 2; switch (option) { case 1: System.out.println("Selected 1"); case 2: System.out.println("Selected 2"); case 3: System.out.println("Selected 3"); default: System.out.println("Not selected"); } } } Selected 2 Selected 3 Not selected
public class Main { public static void main(String[] args) { int option = 2; switch (option) { case 1: System.out.println("Selected 1"); break; case 2: case 3: System.out.println("Selected 2, 3"); break; default: System.out.println("Not selected"); break; } } }
switch表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class Main { public static void main(String[] args) { String fruit = "apple"; switch (fruit) { case "apple" -> System.out.println("Selected apple"); case "pear" -> System.out.println("Selected pear"); case "mango" -> { System.out.println("Selected mango"); System.out.println("Good choice!"); } default -> System.out.println("No fruit selected"); } } }
while循环
1 2 3 4 5 6 7 8 9 10 11
public class Main { public static void main(String[] args) { int sum = 0; // 累加的和,初始化为0 int n = 1; while (n <= 100) { // 循环条件是n <= 100 sum = sum + n; // 把n累加到sum中 n ++; // n自身加1 } System.out.println(sum); // 5050 } }
public class Main { public static void main(String[] args) { int sum = 0; int n = 1; do { sum = sum + n; n ++; } while (n <= 100); System.out.println(sum); } }
public class Main { public static void main(String[] args) { int sum = 0; for (int i=1; ; i++) { sum = sum + i; if (i == 100) { break; } } System.out.println(sum); } }
public class Main { public static void main(String[] args) { int sum = 0; for (int i=1; i<=10; i++) { System.out.println("begin i = " + i); if (i % 2 == 0) { continue; // continue语句会结束本次循环 } sum = sum + i; System.out.println("end i = " + i); } System.out.println(sum); // 25 } }
数组操作
Java标准库提供了Arrays.toString()遍历数组
int[] s = {6,1,12,4,5,33};
int sum = 0;
System.out.println(Arrays.toString(s));
[6, 1, 12, 4, 5, 33]