发布于2024.7.13
顺序控制
分支控制
分为单分支、双分支、多分支。
if else
嵌套分支:ifelse里面嵌套ifelse。最多不要多于三层,不好阅读。
switch
三个使用细节:
重点:细节二!
细节一:
具体实现:
char c1 = sc.next().charAt(0);
switch(c1){
case 97 :
System.out.println("Monday");
break;
case 'b' :
System.out.println("Tuesday");
break;
如上,char可以自动转成int型,所以case 97可行。
练习:
Scanner sc = new Scanner(System.in);
System.out.println("input:");
int i = sc.nextInt();
switch(i){
case 3 :
case 4 :
case 5 :
System.out.println("Spring");
break;
case 6 :
case 7 :
case 8 :
System.out.println("Summer");
break;
case 9 :
case 10 :
case 11 :
System.out.println("Autumn");
break;
case 12 :
case 1 :
case 2 :
System.out.println("Winter");
break;
}
循环控制
for
使用细节:
编程思想(先死后活):
转变为:
先死后活的思想:很重要!
int count = 0;
int start = 1;
int end = 100;
for(int i = start; i <= end; i++){
if((i % 9) == 0){
System.out.println(i);
count++;
}
}
System.out.println("num: " + count);
while
do while
多重循环
练习题:
空心金字塔
package HackerDemo;
import java.util.Scanner;
public class Demo240705 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 1; i < n ;i++){
for(int j = 1; j <= n-i; j++){
System.out.print(" ");
}
if(i==1){
System.out.println("*");
}
else{
System.out.print("*");
for(int k = 1; k <= (i - 2) * 2 + 1; k++){
System.out.print(" ");
}
System.out.println("*");
}
}
for(int i = 0 ;i < 2*n-1;i++){
System.out.print("*");
}
}
}
break
break与标签:实际应用尽量不要用,可读性差。
lable1:
for(int i = 0; i < 10; i++){
abc2://可以随意自己命名
for(int j = 0; j < 10; j++){
if(i == 2){
System.out.println("ok");
break lable1;
}
if(i==3){
System.out.println("nook");
}
}
}
continue
和 break一样,也可以用标签来指定继续的循环体。