You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. The outer loop runs 3 times (once per row).
  2. For each row, the inner loop prints "x" 5 times without newlines, resulting in xxxxx on a single line.
  3. After the inner loop finishes, System.out.println() moves the cursor to the next line.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:12:39