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
Scannerto read the integer input from the user—this tells us how big the square should be. - For Loop for Rows: The
forloop runs exactlysizetimes, once for each row in the square. Therowvariable keeps track of which row we're on. - While Loop for Columns: Inside each row, we initialize a
columnvariable to 0. Thewhileloop runs untilcolumnreachessize, printing a*each time and incrementingcolumn—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
相关产品推荐
相关产品推荐

