if语句
语法格式:
if(表达式){
若干语句
}
例:
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n%2==0){
System.out.println("even");
}
if(n%2!=0){
System.out.println("old");
}
}
}
if-else语句
if(表达式){
若干语句
}else{
若干语句
}
例:
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n%2==0){
System.out.println("even");
}else{
System.out.println("old");
}
}
}
if-else if-else 语句
if(表达式){
若干语句
}else if(表达式){
若干语句
}
...
else{
若干语句
}
例:
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n%3==0){
System.out.println("YES");
}else if(n%5==0){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
switch语句
JDK17之前:
switch(表达式){
case 常量值1:
若干语句
break;
case 常量值2:
若干语句
break;
...
case 常量值n:
若干语句
break;
default:
若干语句
}
例:
a*b mod c = (a mod c)*(b mod c)mod c
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
a %= 7;
int ans = 1;
for(int i=1;i<=b;i++){
ans *= a;
ans %= 7;
}
switch(ans){
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
default:
System.out.println("发生错误");
}
}
}
JDK17之后增加了一个新特性:
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
a %= 7;
int ans = 1;
for(int i=1;i<=b;i++){
ans *= a;
ans %= 7;
}
switch(ans){
case 0->{
System.out.println("Sunday");
}
case 1-> {
System.out.println("Monday");
}
case 2-> {
System.out.println("Monday");
}
case 3-> {
System.out.println("Wednesday");
}
case 4-> {
System.out.println("Thursday");
}
case 5->{
System.out.println("Friday");
}
case 6-> {
System.out.println("Saturday");
}
default->{
System.out.println("发生错误");
}
}
}
}