顺序结构
- 从上到下顺序执行。
选择结构
- if单选择结构
实列:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("input:");
String s = scan.nextLine();
//equals 判断字符串是否相等
if (s.equals("hello")){
System.out.println(s);
}
System.out.println("end");
scan.close();
}
- if双选择结构
实例:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//分数大于90及格,小于90不及格
System.out.println("input score:");
int score = scan.nextInt();
if (score>90){
System.out.println("及格");
}else {
System.out.println("不及格");
}
scan.close();
}
if多选择结构
实例:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("input score:");
int score = scan.nextInt();
if (score==100){
System.out.println("满分!");
}else if (score>=90&&score<100) {
System.out.println("A");
}else if (score>=60&&score<90) {
System.out.println("B");
}else if (score<60&&score>=0) {
System.out.println("不及格");
}else {
System.out.println("输入不合法!");
}
scan.close();
}
嵌套if结构
switch多选择结构
实例
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("input your grade:");
/*Scanner本身并不支持获取char类型的数据
但是可以通过charAt()方法截取string的首位来获取char类型的数据
charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。*/
char grade = scan.next().charAt(0);
switch (grade){
//case穿透,不加break会返回之后的所有case包括default swith匹配具体的值
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("一般");
break;
case 'D':
System.out.println("及格");
break;
case 'E':
System.out.println("再接再厉");
break;
default:
System.out.println("未知参数");
}
scan.close();
}
循环结构
while循环
实例:
public static void main(String[] args) {
//输出1~10
int i = 0;
while (i<10){
i++;
System.out.println(i);
}
}
public static void main(String[] args) {
//计算 1+2+3+。。1000
int i = 0;
int sum = 0;
while (i<=1000){
sum = sum + i;
i++;
}
System.out.println(sum);
}
do…while循环
实例:
public static void main(String[] args) {
int i = 0;
int sum = 0;
do{
sum = sum + i;
i++;
}while(i<=100);
System.out.println(sum);
}