这是最基础的例子了,每个初学者都会要做这个题目。这个题目的目的是熟悉循环特 别是嵌套循环的使用。但是如果对 Java 足够熟悉,回头来再写这个程序,就完全不是这 么写的了。
嵌套循环是非常复杂的逻辑。特别是写得很长的嵌套循环,一个不小心把 j 写成 i, 就够你调试半天的。所以嵌套循环应该尽量避免。怎么避免?将内部循环提取成一个方法 。这样每个方法里都只有一层循环,容易看,容易改,而且不容易出错。
import java.util.Arrays;/** * 打印一个字符组成的金字塔 */public class Pyramid { // 程序入口 public static void main(String[] args) { printPyramid(21, '*'); } /** * 打印一座金字塔。 * * @param bottom_width 底层宽度。必须是奇数。 * @param ch 组成金字塔的字符 */ private static void printPyramid(int bottom_width, char ch) { if (bottom_width < 1 || bottom_width % 2 == 0) { throw new IllegalArgumentException(); } int height = bottom_width / 2 + 1; // 金字塔的高度 for (int i = 0; i < height; i++) { int width = i * 2 + 1; // 本层的宽度 System.out.println(getLevel(bottom_width, width, ch)); } } /** * 生成金字塔的一行 * * @param bottom_width 金字塔宽度 * @param width 本层的宽度 * @param ch 要打印的字符 * * @return 金字塔的一行 */ private static String getLevel(int bottom_width, int width, char ch) { int space_width = (bottom_width - width) / 2; // 前面空格的宽度 return expand(' ', space_width) + expand(ch, width); } /** * 生成包含若干个字符的字符串。 * * @param c 生成字符串的字符 * @param width 字符串的长度 * * @return 生成的字符串 */ private static String expand(char c, int width) { char[] chars = new char[width]; Arrays.fill(chars, c); return new String(chars); }}
看完你可能觉得奇怪:这里有嵌套吗? 有。Arrays.fill() 方法最终就是通过循环实 现的。
去旅行不在于记忆,而在于当时的那份心情。