目标:
- 熟练使用for循环,并体会for循环的特点。
一、使用for循环打印一个固定高度(高度为9)的金字塔
final static int HEIGHT = 9; //用常量HEIGHT定义高度
public static void printMyPyramid() {
for (int h = 0; h <= HEIGHT ; h++) { //h控制金字塔高度
for (int b = HEIGHT - h; b > 0; b--) { //b控制前方空格数量
System.out.print(" ");
}
for (int w = 0; w < 2 * h - 1; w++) { //w控制星星宽度
System.out.print("*");
}
System.out.println();
}
}
结果展示:
二、使用for循环打印一个高度可变的金字塔
public static void printMyPyramid(int height) {
for (int h = 0; h <= height; h++) { //h控制金字塔高度变化
for (int b = height - h; b > 0; b--) { //b控制前方空格数量
System.out.print(" ");
}
for (int w = 0; w < 2 * h - 1; w++) { //w控制星星宽度
System.out.print("*");
}
System.out.println();
}
}
结果展示:
高度为3:
高度为5:
高度为12:
三、使用for循环写出一个可以控制树冠高度的圣诞树
public static void printMyTree(int high) {
for (int h = 0; h <= high; h++) { //h控制树冠高度
for (int b = high - h; b > 0; b--) { //b控制树冠前方空格数量
System.out.print(" ");
}
for (int j = 0; j <= 2 * h; j++) { //j空格树冠星号数量,乘2可也用按位左移1位替代
System.out.print("*");
}
System.out.println();
}
for (int s = 0; s <= (high << 1) / 3; s++) {//按位左移1位,等同于乘2的1次方,后文乘2均可用按位左移1位替代
for (int t = 0; t < 2 * high; t++) {
if ((t == 2 * high / 6 || t == 2 * high - (2 * high / 6)) && s < high/5) { //确定打印装饰'$'的长度、位置,保证每次出现位置大致为两侧中心
System.out.print("$");
} else if (t >= 2 * high / 3 +1 && t <= 2 * high-(2 * high / 3 +1)) { //确定打印树桩'#'的长度、位置
System.out.print("#");
} else {//其余部分打印空格代替(将树桩、装饰推至正中心)
System.out.print(" ");
}
}
System.out.println();
}
}
结果展示:
树冠高度为2:
树冠高度为5:
树冠高度为6:
树冠高度为11:
以此类推,装饰的长度会随着圣诞树的高度而变化。
总结:
⭐ for循环一般形式为:
for(单次表达式;条件表达式;末尾循环体){
//每次循环将执行的语句
}
⭐ for循环特点:以计数是否符合要求为判断条件。
⭐ for循环执行末尾循环体后将再次进行条件判断,若条件还成立,则继续重复上述循环,当条件不成立时则跳出for循环。
⭐ for循环在解决双重问题时候可以嵌套使用(如打印金字塔那样)。
⭐ for循环在解决需要复杂判断时可以结合if使用(如打印圣诞树那样)
⭐ for循环最简形式(但这会造成死循环,一般使用 while(true) )
for(;;){
中间循环体 //将会无限重复执行
}