省流:和C++的判断语句大差不差
判断语句
- 基本结构
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
if (a > b) {
if (a > c)
System.out.println(a);
else
System.out.println(c);
} else {
if (b > c)
System.out.println(b);
else
System.out.println(c);
}
}
}
- 常用比较运算符
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");
}
}
}
条件表达式
- 与 &&
- 或 ||
- 非 !
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 % 4 == 0 && year % 100 != 0 || year % 400 == 0)
System.out.println("yes");
else
System.out.println("no");
}
}
switch 语句
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);
}
}
注意:swtich语句中如果不加break语句,则从上到下匹配到第一个case后,会顺次执行后面每个case中的语句。