结构
1.顺序结构
-
JAVA的基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行。
-
顺序结构是最简单的算法结构。
-
语句语句之间,框与框之间是按从上到下的顺序进行的,它是由若干个依次执行的处理步骤组成的,他是任何一个算法都离不开的一种基本算法结构。
-
package com.chayidian.struct; public class Demo01 { public static void main(String[] args) { System.out.println("hello1"); System.out.println("hello2"); System.out.println("hello3"); System.out.println("hello4"); } }
2.选择结构
-
if双选择结构
需求:公司要收购一个软件,成功了,给人支付100万元,失败了,自己众人开发。这样的需求用一个if就不定了,我们需要有俩个判断,需要一个双选择结构,所以就有了if-else结构
语法:
if(布尔表达式){
//如果布尔表达式的值未true
}else{
//如果布尔表达式的值为false
}
IfDemo01 package com.chayidian.struct; import sun.nio.cs.ext.DoubleByte; 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(); //quals: 判断字符串是否相等 if(s.equals("hello")){ System.out.println(s); } System.out.println("End"); scanner.close(); } }
-
if多选择结构
-
当我们发现刚才的代码不符合实际情况,真是的情况还可能存在ABCD,存在区间多级判断。比如90-100就是A,80-90就是B。。。等等,在生活中我们很多时候的选择也不仅仅只有俩个,所以我们需要一个多选择结构来处理这类问题!
-
语法:
if(布尔表达式 1){
//如果布尔表达式 1值为true执行代码
}else if(布尔表达式 2){
//如果布尔表达式 2值为true执行代码
}else if(布尔表达式 3){
//如果布尔表达式 3值为true执行代码
}
-
-
IfDemo02
-
package com.chayidian.struct; 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(); } }
-
嵌套的if结构
-
使用嵌套的if...else语句是合法的。也就是说可以在另一个if后者else if语句使用if或else if 语句。可以像if语句一样嵌套else if...else。
-
语法:
if(布尔表达式 1){
///如果布尔表达式1的值为true执行代码
if(布尔表达式 2){
///如果布尔表达式 2的值为true执行代码
}
}
IfDemo03
-
-
package com.chayidian.struct; 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 语句至多1个 else 语句,else 语句在所有的else if语句之后 if 语句可以有若干个else if 语句,他们必须在else之前。 一旦其中一个else if 语句检测为true,其他的else if 以及else 语句都将跳过执行。 */ if (score==100){ System.out.println("恭喜满分"); } else if (score<100&&score>=90){ System.out.println("考试等级为A"); }else if(score>=80&&score<90){ 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){ System.out.println("考试成绩不及格!"); } else { System.out.println("考试成绩不合法"); } scanner.close(); } }