今天复习了java的判断语句
1. 基本if-else语句
当条件成立时,执行某些语句;否则执行另一些语句
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if (a > 5) { System.out.printf("%d is big!\n", a); System.out.printf("%d + 1 = %d\n", a, a + 1); } else { System.out.printf("%d is small!\n", a); System.out.printf("%d - 1 = %d\n", a, a - 1); } } }
当只有一条语句时,大括号可以省略:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if (a > 5) System.out.printf("%d is big!\n", a); else System.out.printf("%d is small!\n", a); } }
练习:
1.判断闰年。闰年有两种情况:
(1) 能被100整除时,必须能被400整除;
(2) 不能被100整除时,被4整除即可。
输入一个年份,如果是闰年输出yes,否则输出no。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int year = sc.nextInt(); if (year % 100 == 0) { if (year % 400 == 0) System.out.println("yes"); else System.out.println("no"); } else { if (year % 4 == 0) System.out.println("yes"); else System.out.println("no"); } } }
switch 语句
注意: swtich语句中如果不加break语句,则从上到下匹配到第一个case后,会顺次执行后面每个case中的语句。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int day = sc.nextInt(); String name; switch(day) { case 1: name = "Monday"; break; case 2: name = "Tuesday"; break; case 3: name = "Wednesday"; break; case 4: name = "Thursday"; break; case 5: name = "Friday"; break; case 6: name = "Saturday"; break; case 7: name = "Sunday"; break; default: name = "not valid"; } System.out.println(name); } }
标签:总结,case,name,22,System,Scanner,public,out From: https://www.cnblogs.com/liucaizhi/p/17145630.html