如何编写程序打印指定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
heightandwidthto 0, then use awhileloop 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
heighttimes 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
相关产品推荐
相关产品推荐

