本节内容教学视频链接:Java流程控制04:if选择结构_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV12J41137hu?p=36&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5
在Java中,if
选择结构用于根据特定条件执行不同的代码块。
if语句有四种结构:if单选择结构、if双选择结构、if多选择结构、if嵌套结构;
1.if单选择结构(if)
代码示例1:单选择结构
import java.util.Scanner;
public class IfDemo01 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容");
String s = scanner.nextLine();
if (s.equals("Hello")){
System.out.println(s);
}
System.out.println("End");
scanner.close();
}
}
代码示例2:单选择结构
int number = 10;
if (number > 0) {
System.out.println("Number is positive");
}
2.if双选择结构(if...else
)
代码示例1:
import java.util.Scanner;
public class IfDemo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩");
int score = scanner.nextInt();
if (score>60){
System.out.println("成绩及格");
}else{
System.out.println("成绩不及格");
}
scanner.close();
}
}
代码示例2:
int number = -10;
if (number > 0) {
System.out.println("Number is positive");
} else {
System.out.println("Number is non-positive");
}
3.if多选择结构(if...else if...else
)
代码示例1:
import java.util.Scanner;
public class IfDemo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入考生成绩");
int score = scanner.nextInt();
if (score==100){
System.out.println("恭喜您获得满分!!!");
} else if (score<100 && score>=90) {
System.out.println("您的成绩为A");
} else if (score<90 && score>=80) {
System.out.println("您的成绩为B");
} else if (score<80 && score>=70) {
System.out.println("您的成绩为C");
} else if (score<70 && score>=60) {
System.out.println("您的成绩为D");
} else if (score<60 && score>=0) {
System.out.println("您的成绩不及格,请再接再厉");
}else {
System.out.println("您的输入的成绩不合法");
}
}
}
代码示例2:
int number = 25;
if (number <= 0) {
System.out.println("Number is non-positive");
} else if (number < 10) {
System.out.println("Number is between 1 and 10");
} else {
System.out.println("Number is greater than 10");
}
3.if嵌套结构
int x = 10;
int y = 20;
if (x > 0) {
if (y > 0) {
System.out.println("Both x and y are positive");
} else {
System.out.println("x is positive and y is non-positive");
}
} else {
if (y > 0) {
System.out.println("x is non-positive and y is positive");
} else {
System.out.println("Both x and y are non-positive");
}
}