如何用不超过4个for循环实现沙漏镜像(含半沙漏补全,禁用递归与数组)
Mirrored Hourglass with 4 For Loops (No Recursion/Arrays)
Alright, let's get this sorted! You want to complete a mirrored hourglass using no more than 4 for loops (no recursion or arrays allowed), and we can build on your existing code to make it work. Here's the full, working code, plus a breakdown of how it all comes together:
import java.util.Scanner; public class Hourglass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter odd number above 0 here: "); int h = sc.nextInt(); char x = '#'; if (h % 2 != 0) { // Upper half (includes the middle narrowest line) for (int i = 0; i <= (h - 1) / 2; i++) { // Print leading spaces to create the "tapering" effect for (int j = 0; j < i; j++) { System.out.print(" "); } // Print the hash symbols for this row for (int j = 0; j < h - 2 * i; j++) { System.out.print(x); } System.out.println(); // Move to next line after each row } // Lower half (mirrors the upper half, excluding the middle line) for (int i = (h - 3) / 2; i >= 0; i--) { // Reuse the same space logic as the upper half for (int j = 0; j < i; j++) { System.out.print(" "); } // Reuse the same hash logic to mirror the row width for (int j = 0; j < h - 2 * i; j++) { System.out.print(x); } System.out.println(); } } else { System.out.println("Please enter an odd number greater than 0!"); } sc.close(); } }
How This Works
- Input Validation: First, we check that the input is an odd number (critical for a symmetric hourglass with a single middle line).
- Upper Half Construction:
- The outer loop runs from
0to(h-1)/2—this covers every row from the widest top line down to the narrow middle line. - The first inner loop prints leading spaces: each row gets
ispaces, so the space count increases as we move toward the middle, creating the tapering effect. - The second inner loop prints the hashes: starting with
hhashes (full width), we subtract2hashes per row (one for each side's space) until we hit the middle line with just1hash.
- The outer loop runs from
- Lower Half Mirroring:
- The outer loop runs from
(h-3)/2down to0—this starts just below the middle line and works back up to the widest bottom line. - We reuse the exact same space and hash logic as the upper half, which automatically mirrors the tapering effect in reverse.
- The outer loop runs from
Example Output (Input = 5)
##### #### ### ## # ## ### #### #####
内容的提问来源于stack exchange,提问作者grinsekatz007
相关产品推荐
相关产品推荐

