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

如何编写程序打印指定XX网格?技术实现咨询

Hey there! Let's build this Java program exactly how you need it. You want a tool that prompts for height and width, validates inputs to ensure they're valid, then prints a grid of X-based cells matching your specified format. Here's the full solution:

Complete Working Code

import java.util.Scanner;

public class Loops {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int height = 0;
        int width = 0;

        // Input validation loop: ensure both values are greater than 1
        while (height <= 1 || width <= 1) {
            // Show error message only after first failed input attempt
            if (height != 0 || width != 0) {
                System.out.println("Invalid height or width value");
            }

            System.out.print("Type in the height: ");
            height = input.nextInt();

            System.out.print("Type in the width: ");
            width = input.nextInt();
        }

        // Create a single "cell" with X's matching the input width
        String cell = "X".repeat(width);

        // Print the grid: repeat the cell 'height' times, separated by spaces
        for (int i = 0; i < height; i++) {
            if (i > 0) {
                System.out.print(" ");
            }
            System.out.print(cell);
        }

        input.close();
    }
}

How It Works

  • Input Handling & Validation: We initialize height and width to 0, then use a while loop to keep asking for inputs until both values are greater than 1. We avoid showing the error message on the first run to keep the initial prompt clean.
  • Cell Creation: Using String.repeat(width), we generate a string of X's that matches the input width (e.g., width=2 gives "XX").
  • Grid Printing: We loop height times to print the cell repeatedly, adding a space before every cell except the first to match your desired output format.

Example Output

Type in the height: 5
Type in the width: 2
XX XX XX XX XX

内容的提问来源于stack exchange,提问作者Keit007

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:27:13