顺序结构
- Java的基本结构,除非特别指明,否则就按照顺序一句一句执行。
- 顺序结构是最简单的算法结构
- 语句与语句之间,框与框之间按从上到下的顺序执行,它是任何算法都离不开的一种基础算法结构。
package struct;
public class ShunXuDemo01 {
public static void main(String[] args) {
//从上到下依次执行
System.out.println("hello1");
System.out.println("hello2");
System.out.println("hello3");
System.out.println("hello4");
System.out.println("hello5");
}
}
选择结构
if单选择结构
-
我们很多时候需要去判断一个东西是否可行,然后再去执行,这样一个过程在程序中用if语句来表示。
-
package struct; import java.util.Scanner; public class ifDemo01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); //equal:判断字符串是否相等 if (s.equals("hello")) { System.out.println(s); } System.out.println("End"); scanner.close(); } }
if双选结构
-
我们需要两个判断,就要用到双选择结构,所以就有了if-else。
package struct; import java.util.Scanner; public class IfDemo02 { public static void main(String[] args) { //考试大于60及格否则不及格 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(); } }
if多选结构
- 有时候要判断不止两个的选择就要用到多选else if
package struct;
import java.util.Scanner;
public class IfDemo02 {
public static void main(String[] args) {
/*
if 语句最多有一个else语句 。else语句在所有else if 之后。
if 语句可以有若干个else if 语句,它们必须再else之前。
一旦其中一个else if 语句检测为true ,其他的else if 或 else 都跳过执行
*/
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("优秀");
}else if(score<90 && score>80){
System.out.println("B优秀");
}else if(score<80 && score>70){
System.out.println("良好");
}else if(score<70 && score>=60){
System.out.println("及格");
}else if(score<60 && score>=0){
System.out.println("不及格");
}else {
System.out.println("成绩不合法");
}
scanner.close();
}
}
嵌套的if结构
- 使用嵌套的if…else语句是合法的。也就是你可以在另一个if 或else if 语句中使用if 或else if。
package struct;
public class IfDemo04 {
public static void main(String[] args) {
int i = 10;
double t = 0;
int j = 20;
if (i>j){
t=t+1;
System.out.println(t);
} if (j>i){
t=t-1;
System.out.println(t);
}
}
}
Switch多选择结构
- 多选择结构还有一个实现方式就是switch case 语句。
- switch case 语句判断一个变量与一系列值中的某个值是否相等,每个值称为一个分支。
- switch case 语句中的变量类型可以是
- byte、short、int或者char
- 从JavaSE 7 开始 switch 支持字符串String类型了
- 同时case标签必须为字符串常量或字面量。
package struct;
public class SwitchDemo01 {
public static void main(String[] args) {
//case穿透不写break会一直向下执行 //switch匹配一个具体的值
char grade = 'C';
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("再接再厉");
}
}
}