1.顺序结构
2.选择结构
//equals:判断字符串是否相等 if(s.equals("hello world!")){ System.out.println(s); }
-
if多选择结构
int score; if(score>=90){ System.out.println("优秀"); }else if(score>=60){ System.out.println("及格"); }elss{ System.out.println("不及格"); }
-
switch多选择结构
int score; switch(score){ case "A": System.out.println("优秀"); break; case "B": System.out.println("及格"); break; case "C": System.out.println("不及格"); break; default: System.out.println("未知等级"); }
3.循环结构
-
while
whlie( 布尔表达式 ){ //循环内容 }
-
do...while
do{ //代码语句 }while( 布尔表达式 );
-
for
for(初始化; 布尔表达式 ; 更新){ //代码语句 }
-
增强for循环 Java5引入了一种主要用于数组或集合的增强型for循环。
for(声明语句 : 表达式){ //代码语句 }
public static void main(String[] args){ int[] numbers = {10,20,30,40,50}; for(int x : numbers){ System.out.println(x); } }
扩展
-
println 输出完会换行
-
print 输出完不会换行
-
4.break、continue
-
break 在任何循环语句中的主体部分,均可用break强制退出循环,不执行循环体中的剩余语句。
-
continue 用于终止某次循环,即跳过循环体尚未执行的语句,接着进行下一次是否执行循环的判定。
-
扩展 :goto关键字 ,( 保留关键字 、标签属性)
//需求:打印101-150之间的质数 public static void main(String[] args){ int count = 0; outer:for(int i = 101 ; i<=150 ; i++){ for(int j = 2 ; j < i/2 ; j++){ if(i %j == 0){ continue outer; } } System.out print(i + ""); } }
5.练习
//需求:打印三角形 5行 public static void main(String[] args){ for(int i = 1 ; i<=5 ; i++){ for(int j = 5 ; j >= i ; j--){ System.out.print(" "); } for(int j = 1 ; j <= i ; j++){ System.out.print("*"); } for(int j = 1 ; j < i ; j++){ System.out.print("*"); } System.out.println(); } }