基于递归实现反射式星号直角三角形的问题求助
Let's figure out why your current code is producing a vertically reversed triangle and how to fix it to match your expected output.
First, let's break down what your existing code does:
- It recursively calls
rightTriangle(n-1)before building and printing the current line - Each line is built by appending a star to the result of the recursive call, starting with a single space from the base case
- This means you end up printing lines from 1 star up to
nstars, which is a left-aligned, increasing triangle — the opposite of the reflected (right-aligned) or vertically reversed (decreasing) triangle you want.
Option 1: Vertically Reversed (Decreasing) Triangle
If your expected output for rightTriangle(4) is this (largest line first):
**** *** ** *
The fix is simple: print the current line first, then recurse on n-1 instead of the other way around. Here's the adjusted code:
public static String rightTriangle(int n){ if( n <= 0 ){ return ""; // Return empty string to avoid extra leading spaces } // Create a line with n stars String line = "*".repeat(n); System.out.println(line); // Recurse on the smaller value after printing rightTriangle(n - 1); return line; }
Note: If you're using Java 10 or earlier (where String.repeat() doesn't exist), replace "*".repeat(n) with a loop to build the star string:
String line = ""; for(int i = 0; i < n; i++){ line += "*"; }
Option 2: Reflected (Right-Aligned) Increasing Triangle
If you want the classic right-aligned reflected triangle for rightTriangle(4):
* ** *** ****
We need to add leading spaces to each line. The number of spaces for line k (where k goes from 1 to n) is n - k. The cleanest way to handle this is with a helper method that tracks both the current line number and the total number of lines:
// Public method for users to call public static void rightTriangle(int n) { if (n <= 0) return; // Start printing from line 1 to line n printRightTriangle(1, n); } // Helper method to handle spacing and recursion private static void printRightTriangle(int currentLine, int totalLines) { if (currentLine > totalLines) return; // Calculate leading spaces: totalLines - currentLine String spaces = " ".repeat(totalLines - currentLine); // Calculate stars for the current line String stars = "*".repeat(currentLine); System.out.println(spaces + stars); // Recurse to print the next line printRightTriangle(currentLine + 1, totalLines); }
This approach keeps track of how many spaces each line needs, ensuring perfect right alignment.
Why Your Original Code Failed
Your base case returned a single space, and you appended stars to that string each time. This created left-aligned lines with an extra leading space, like *, **, etc. By adjusting the recursion order (print first vs recurse first) and adding intentional spacing, we can get the exact reflected triangle you're looking for.
内容的提问来源于stack exchange,提问作者user17080770

