問題是星星不會形成圣誕樹,它們只是形成一個直角三角形。如何解決? https://i.imgur.com/vKpxRhP.png <--- 這就是它的樣子。 https://i.imgur.com/eyuccNn.png <--- 這應該是它的樣子。
public static void main(String[] args) throws FileNotFoundException {
File file = new File("In0103.txt");
Scanner in = new Scanner(file);
int maxWidth = in.nextInt();
int initialWidth = 1;
int initialLevel = 1;
int maxLevel = (maxWidth 1) / 2;
int freeSpace = maxLevel - 1;
printChristmasTree(initialWidth, initialLevel, maxLevel, freeSpace, null);
}
static void printChristmasTree(int width, int level, int maxLevel, int freeSpace, PrintWriter save) throws FileNotFoundException {
if (save == null) {
save = new PrintWriter("Out0103.txt");
}
if (level < maxLevel) {
save.println(Stream.generate(() -> " ").limit(freeSpace).collect(Collectors.joining()));
save.println(Stream.generate(() -> "*").limit(width).collect(Collectors.joining()));
save.println();
printChristmasTree(width = width 2, level, maxLevel, --freeSpace, save);
} else {
save.println(Stream.generate(() -> " ").limit(freeSpace).collect(Collectors.joining()));
save.println(Stream.generate(() -> "*").limit(width).collect(Collectors.joining()));
save.close();
}
}
uj5u.com熱心網友回復:
你幾乎明白了。但是您正在列印freeSpacewithsave.println()但不需要新行,只需save.print(). 此外,還有一個不需要的額外內容save.println():
public static void main(String[] args) throws FileNotFoundException {
File file = new File("In0103.txt");
Scanner in = new Scanner(file);
int maxWidth = in.nextInt();
int initialWidth = 1;
int initialLevel = 1;
int maxLevel = (maxWidth 1) / 2;
int freeSpace = maxLevel - 1;
printChristmasTree(maxWidth, initialWidth, initialLevel, maxLevel, freeSpace, null);
}
static void printChristmasTree(int maxWidth, int width, int level, int maxLevel, int freeSpace, PrintWriter save) throws FileNotFoundException {
if (save == null) {
save = new PrintWriter("Out0103.txt");
save.println("n =" maxWidth "");
}
if (level < maxLevel) {
save.print(Stream.generate(() -> " ").limit(freeSpace).collect(Collectors.joining()));
save.println(Stream.generate(() -> "*").limit(width).collect(Collectors.joining()));
printChristmasTree(maxWidth, width 2, level, maxLevel, --freeSpace, save);
} else {
save.print(Stream.generate(() -> " ").limit(freeSpace).collect(Collectors.joining()));
save.println(Stream.generate(() -> "*").limit(width).collect(Collectors.joining()));
save.close();
}
}
也許您需要將行從 更改int freeSpace = maxLevel - 1;為int freeSpace = maxLevel;,因為您的樹的最后一行似乎有一個可用空間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/356397.html
上一篇:Scala遞回/尾遞回
