三大结构及其用法
一.顺序结构
顺序结构的程序设计是最简单的,只要按照解决问题的顺序写出相应的语句就行,它的执行顺序是自上而下,依次执行.
public static void main(String[] args) {
System.out.println("Hello1");
System.out.println("Hello2");
System.out.println("Hello3");
System.out.println("Hello4");
}
}
上述程序所运行出的结果也是显而易见的.
二. 选择结构
- if选择结构
1.if语句是用来判断所给条件为真或假的语句。
2.if(所判断的条件/条件一){符合条件时所执行的命令;}//唯一性
3.else if(非if中的条件/二){满足条件所执行的命令;}//可出现多个
4.else {条件};//当所给条件既不满足以上所有条件才会执行else语句
public class IfDemoo3 {
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("成绩评级为:s");
}else if (score>=90&&score<100){
System.out.println("成绩评级为:a+");
}else if (score>=80&&score<90){
System.out.println("成绩评级为:a");
}else if (score>=60&&score<80){
System.out.println("成绩评级为a--");
}else {
System.out.println("成绩评级:不合格");
}
scanner.close();
}
}
- switch case选择结构
1.switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支.
2.switch case语句具有穿透性.
3.switch(name){
case 值1:命令1;
break;
case 值2:命令2;
break;
…
…
}
public static void main(String[] args) {
String 童罗焜 = "倔强青铜";
switch(童罗焜){
case "最强王者" :
System.out.println("夸大其词");
break;
case "倔强青铜" :
System.out.println("正中下怀");
break;
case "倔强王者" :
System.out.println("小了,小了,格局小了");
break;
}
}
}
运行结果为:
三.循环结构
- while循环结构
1.while是最基本的循环.
2.只要布尔表达式为:true,循环就会一直下去.
3.while语句在判段条件不成立时不会进入循环,而do while语句至少进入循环一次.
4.while(布尔表达式){循环语句;}
do{代码语句} while(布尔表达式;)
public static void main(String[] args) {
int i = 0;
int sum = 0;
while(i<0){
System.out.println(i);
i++;
}
System.out.println("=============================================================");
do {
System.out.println(i);
i++;
} while (i<0);
}
}