第五天:程序结构
Less is more
学习内容
顺序结构
是最简单的基本结构,除非特别指明,否则就按照顺序一句一句执行
选择结构
if选择
1 2 3 4 5 6
| if(boolean){ } else { }
|
1 2 3 4 5 6 7 8 9 10
| if(condition1){ } else if(condition2) { } else if(condition3){ } else { }
|
switch选择
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| switch(expression){ case value1 : break; case value2 : break; case value3 : break; default : }
|
IDEA可以直接查看.class文件
循环结构
while循环
1 2 3
| while(boolean==ture){ }
|
do…while循环
1 2 3 4
| do{ } while (expression)
|
for循环
1 2 3 4 5
| for(initial; boolean; update){ }
|
九九乘法表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.joker_yue.javalearn.loopStruct;
public class jiujiu { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j < 10; j++) { System.out.print(j+"*"+i +"="+i*j+'\t'); if(i==j) { System.out.println(); break; } } } } }
|
增强for循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.joker_yue.javalearn.loopStruct;
public class forLoopPlus { public static void main(String[] args) { int[] numbers = {10,20,30,40,50};
for(int x:numbers){ System.out.println(x); }
System.out.println("==========");
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } }
|
break & continue & goto
break 用于跳出此层循环
continue用于跳过此次循环
goto用于跳转,不建议使用,会影响代码的连续性
打印三角形
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.joker_yue.javalearn.loopStruct;
import java.util.Scanner;
public class loopTraining { public static void main(String[] args) { Scanner sc = new Scanner(System.in);
System.out.println("请输入等腰三角形的高"); int n = sc.nextInt();
for (int lines = 0; lines < n; lines++) { for (int spaces = n - lines; spaces > 0; spaces--) { System.out.print(" "); } for (int stars = 0; stars < lines * 2 - 1; stars++) { System.out.print("*"); } System.out.println(); } } }
|