我的任务是编写一个程序,提示用户输入正数,然后绘制星号块(*)以形成楼梯。第一个块的长度和宽度应该是输入的数字。下一个块应该加倍该大小,依此类推,直到显示的块数等于输入的数量。
import java.util.Scanner;
public class Lab1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number of length and width of the first blocks and I will draw some stairs!");
int number = keyboard.nextInt();
for (int i =0; i<number; i++) {
for (int j=0; j<number; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
输入3的示例输出:
3
...
...
...
......
......
......
......
......
......
.........
.........
.........
.........
.........
.........
.........
.........
答案 0 :(得分:2)
您只需要在步骤大小上添加另一个循环。
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number of length and width of the first blocks and I will draw some stairs!");
int number = keyboard.nextInt();
for (int n = 1; n <= number; n++) { // loop over the steps
for (int i = 0; i < n * number; i++) { // for each step, make a rectangle of length "n * number"
for (int j = 0; j < n * number; j++) {
System.out.print("*");
}
System.out.println("");
}
}
答案 1 :(得分:1)
此算法使用最小 for-loops
和一个条件语句,因此;应该为你想要达到的目标做得很好:
import java.util.Scanner;
public class TestMain {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number of length and width of the first blocks and I will draw some stairs! ");
int n = keyboard.nextInt();
int count = n;
int temp = n;
for (int i = 1; i<=n*n*(n+1)/2; i++) {
for (int j=0; j<temp; j++) {
System.out.print("*");
}
count++;
if(count%temp==0) {
temp = temp+n;
count = 0;
}
System.out.println();
}
}
}