顺序控制
按着顺序一个一个运行
选择结构
-
if单选结构
package com.zhaowei.example.struct;
import java.util.Scanner;
//if 单选结构
public class Demo1 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入内容:");
String str=scanner.nextLine();
//equals判断字符串是否相等
if(str.equals("Hello")){
System.out.println(str);
}
System.out.println("End");
scanner.close();
}
}
-
if 双选择结构
package com.zhaowei.example.struct;
import java.util.Scanner;
public class Demo2 {
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多选择结构
package com.zhaowei.example.struct;
import java.util.Scanner;
public class Demo3 {
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("恭喜满分");
}
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){
System.out.println("不及格");
}
else{
System.out.println("成绩不合法");
}
}
}
-
嵌套的if结构
package com.zhaowei.example.struct;
import java.util.Scanner;
public class Demo4 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int guess=(int)(Math.random()*100+1);
System.out.println("请输入一个数:"+guess);
while(true){
int num=scanner.nextInt();
if(num<guess){
System.out.println("小了");
}
else if(num>guess){
System.out.println("大了");
}
else{
System.out.println("猜对了");
}
}
}
}
-
switch多选择结构
package com.zhaowei.example.struct;
public class Demo5 {
public static void main(String[] args) {
//
char grade='C';
switch (grade){
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("及格");
break;
case 'E':
System.out.println("不及格");
default:
System.out.println("成绩等级不知道");
break;
}
}
}
//jdk7以后可以用表示字符串!!!
package com.zhaowei.example.struct;
public class Demo6 {
public static void main(String[] args) {
String name="zhao";
switch (name){
case "zhao":
System.out.println("zhao");
break;
case "zw":
System.out.println("zw");
break;
default:
System.out.println("不知道");
break;
}
}
}
-