就按照顺序一句一句执行。
顺序结构是最简单的算法结构。
- 语句与语句之间,框与框之间是按从上到下的顺序进行的,它是由若干个依次执行的处理步骤组成的,它是任何一个算法都离不开的一种基本算法结构。
package com. kuang.struct;
public class shunXuDemo {
public static void main(String[] args) {
System.out.println("hello1");
System.out.println("hello2");
System.out.println("hello3");
System.out.println("he1lo4");
System.out.println("he11o5");
}
}
hello1
hello2
hello3
hello4
hello5
选择结构
- if单选择结构
- if双选择结构
- if多选择结构
- 嵌套的if结构
- switch多选择结构
if单选择结构
public class IfDemo01 {
public static void main( String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.prinln("请输入内容:");
String s = scanner.nextLine( );
//equals:判断字符串是否相等
if (s.equals("He11o")){
System.out.prinln(s);
}
System.out.println("End");
scanner.close();
}
}
请输入内容:
Hello
Hello
End
if双选择结构
public class IfDemo02 {
public static void main( String[] args) {
//考试分数大于60就是及格,小于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();
}
}
请输入成绩:
80
及格
if多选择结构
-
我们发现刚才的代码不符合实际情况,真实的情况还可能存在ABCD,存在区间多级判断。比如90-100就是A,80-90就是B..等等,在生活中我们很多时候的选择也不仅仅只有两个,所以我们需要一个多选择结构来处理这类问题!
-
语法:
if(布尔表达式 1){
//如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){
//如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){
//如果布尔表达式 3的值为true执行代码
}else {
//如果以上布尔表达式都不为true执行代码
}
public class IfDemo03 {
public static void main( String[] args) {
//考试分数大于60就是及格,小于60分就不及格。
Scanner scanner = new Scanner(System.in);
/*
if 语句至多有1个 else 语句,else 语句在所有的 else if 语句之后。
if 语句可以有若干个 else if 语句,它们必须在 else 语句之前。
一旦其中一个 else if 语句检测为true,其他的 else if 以及 etse 语句都将跳过执行。
*/
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("成绩不合法");
}
scanner.close();
}
}
嵌套的if结构
switch多选择结构
switch(expression){
case value :
//语句
break; //可选
case value :
//语句
break; //可选
//你可以有任意数量的case语句
default : //可选
//语句
}
packag