选择结构
- 单if选择结构
import java.util.Scanner;
public class IfDemo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
if (str.equals("hello")){
System.out.println("执行了if里面");
}
System.out.println("if外面");
scanner.close();
}
}
- if双分支结构
public class IfDemo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
if (str.equals("a")){
System.out.println("成功");
}else {
System.out.println("失败");
}
scanner.close();
}
}
- if多选择结构
public class IfDemo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入你的成绩:");
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("成绩不合法!");
}
scanner.close();
}
}
- switch匹配一个具体的值
public class SwitchDemo01 {
static String grade = "A";
public static void main(String[] args) {
switch (grade) {
case "A":
System.out.println("优秀");
break;
case "B":
System.out.println("良好");
break;
case "C":
System.out.println("及格");
break;
case "D":
System.out.println("不及格");
break;
default:
System.out.println("输入不合法!");
break;
}
}
}
- JDK1.7以后,switch支持string
public class SwitchDemo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
switch (str) {
case "中国":
System.out.println("加油!");
break;
case "武汉":
System.out.println("必胜!");
break;
default:
System.out.println("输入错误");
break;
}
}
}