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

Java实现指定大小的*正方形:需使用for与while循环

Java Program to Print a Star Square Using Both For and While Loops

Hey there! Let's build this program together. The goal is to get a square size from the user, then print a grid of *s that matches that size—plus we need to use both for and while loops. Here's a straightforward implementation that does exactly that:

Full Code

import java.util.Scanner;

public class StarSquare {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Ask user for square size
        System.out.print("Enter the size of the square: ");
        int size = scanner.nextInt();
        
        // Use for loop to handle each row of the square
        for (int row = 0; row < size; row++) {
            // Use while loop to print each star in the current row
            int column = 0;
            while (column < size) {
                System.out.print("*");
                column++;
            }
            // Move to the next line after finishing a row
            System.out.println();
        }
        
        scanner.close();
    }
}

How It Works

Let's break down the key parts:

  • Getting User Input: We use Scanner to read the integer input from the user—this tells us how big the square should be.
  • For Loop for Rows: The for loop runs exactly size times, once for each row in the square. The row variable keeps track of which row we're on.
  • While Loop for Columns: Inside each row, we initialize a column variable to 0. The while loop runs until column reaches size, printing a * each time and incrementing column—this fills the row with stars.
  • New Line After Each Row: After the while loop finishes a row, we call System.out.println() to move to the next line, so the next row starts below.

Example Output

If you enter 3 when prompted, the program will output:

***
***
***

Optional: Add Input Validation

If you want to make the program more robust, you can add a check to ensure the user enters a positive integer. Here's a quick addition:

// Validate input is positive
while (!scanner.hasNextInt() || scanner.nextInt() <= 0) {
    System.out.print("Please enter a positive integer: ");
    scanner.next(); // Clear invalid input
}
int size = scanner.nextInt();

This makes sure the program doesn't crash if the user enters something non-numeric or a negative number.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:11:22