用户输入要创建的正方形数。用户还通过输入尺寸来指定每个正方形的尺寸。然后,程序在屏幕上以用户指定的大小打印出带有星星的正方形。正方形应按顺序绘制。
在下面的示例中,打印出3个正方形,大小分别为5x5、3x3和7x7。
输出应如下所示:
输入形状数量:3 输入形状1:5的大小 输入形状2的大小:3 输入形状3的大小:7
我的第一次尝试可以,但是在输入一定数量的正方形后立即打印正方形。像这样-
import java.util.Scanner;
public class Main3 {
static Scanner scanner = new Scanner(System.in);
static int numOfShapes;
static String[] shape;
static int shapeSize;
static int nrOfRows;
static int nrOfCols;
public static void main(String[] args) {
System.out.print("Enter the number of shapes:");
numOfShapes = scanner.nextInt();
scanner.nextLine();
getShape();
}
public static void getShape(){
for(int i = 0; i < numOfShapes; i++){
System.out.print("Enter size of shape " + (i + 1) + "\n");
shapeSize = scanner.nextInt();
scanner.nextLine();
shape = new String[shapeSize];
nrOfRows = shapeSize;
nrOfCols = shapeSize;
for (int row = 0; row < nrOfRows; row++) {
for (int col = 0; col < nrOfCols; col++) {
shape[i] = "*";
System.out.printf("%s ", shape[i]);
}
System.out.println();
}
}
}
}
我的第二次尝试看起来像这样,但似乎无法正常工作。我不知道为什么。
导入java.util.Scanner;
公共类主要{
static int numOfShapes;
static int sizeOfShape;
static String[] arrayToPrint;
static Scanner scanner = new Scanner(System.in);
static int nrOfRows;
static int nrOfCols;
public static void main(String[] args) {
System.out.print("Enter the number of shapes to print:");
numOfShapes = scanner.nextInt();
for (int i = 0; i < numOfShapes; i++) {
System.out.println("Enter the size of shape " + (i + 1));
sizeOfShape = scanner.nextInt();
scanner.nextLine();
arrayToPrint = new String[sizeOfShape];
//arrayToPrint[i] = Integer.toString(sizeOfShape);
}
nrOfRows = sizeOfShape;
nrOfCols = sizeOfShape;
for (int i = 0; i < numOfShapes; i++) {
for (int row = 0; row < nrOfRows; row++) {
for (int col = 0; col < nrOfCols; col++) {
arrayToPrint[i] = "*";
System.out.printf("%s ", arrayToPrint[i]);
System.out.println();
}
System.out.println();
}
//System.out.println();
}
}
}