Java矩形打印异常问题:如何通过嵌套循环修正输出图案?
Fixing Your Rectangle Printing Code with Nested Loops
Absolutely! Let's start by breaking down why your current code isn't producing the rectangle you want. Right now, your printHeight method prints h separate lines each with one "x", then printWidth prints one line with w "x"s. That's why you're getting a stack of single x's followed by a single long line—definitely not the rectangular pattern you're aiming for.
Nested loops are exactly the right fix here. Here's the core idea:
- The outer loop handles the height of the rectangle (how many rows we need to print).
- The inner loop handles the width of each row (how many "x"s we print per line).
Here's the corrected code:
import java.util.Scanner; public class RectanglePrinter { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter width: "); int w = input.nextInt(); System.out.print("Enter height: "); int h = input.nextInt(); printRectangle("x", w, h); // Call our dedicated rectangle-printing method } private static void printRectangle(String symbol, int width, int height) { // Outer loop: runs once for each row (total of 'height' rows) for (int i = 1; i <= height; i++) { // Inner loop: prints the symbol 'width' times in the current row for (int j = 1; j <= width; j++) { System.out.print(symbol); // No newline here—keep symbols on the same line } System.out.println(); // After finishing the row, move to the next line } } }
How This Works
Let's say you input width=5 and height=3:
- The outer loop runs 3 times (once per row).
- For each row, the inner loop prints "x" 5 times without newlines, resulting in
xxxxxon a single line. - After the inner loop finishes,
System.out.println()moves the cursor to the next line. - Repeat until all 3 rows are printed, giving you this perfect rectangle:
xxxxx xxxxx xxxxx
This approach keeps your logic clean in one focused method, and the nested loops directly map to the rows and columns of a rectangle—exactly what you need.
内容的提问来源于stack exchange,提问作者Trung
相关产品推荐
相关产品推荐

