我想画一个金字塔,从1到用户输入的数字。我现在试过了
static Scanner s=new Scanner(System.in);
static ArrayList<Integer> by;
public static void main (String[] args){
by=new ArrayList<>();
System.out.println("Enter Number : ");
int no=s.nextInt();
while (no > 9 || no==0){
System.out.println("Value cannot be equal to 0 or greater than 9 \nEnter another number");
no=s.nextInt();
}
System.out.println();
for (int a=1;a<=no;a++){
if (a==1){}else{
by.add(a-1);}
Collections.sort(by);
for (int o:by){
System.out.print(o+" ");
}
System.out.print(a);
System.out.println();
}
}但是,我目前还在研究如何把这些数字形成金字塔。我很感谢你的帮助。这是一个金字塔的例子(我用的是c#)

发布于 2013-12-03 16:48:29
以免说用户选择了3,所以您的结果如下
1
1 2
1 2 3虽然它应该
1
1 2
1 2 3所以你需要把每一行都移到右边
__1 //move two characters to right
_1 2 //move one character to right
1 2 3 //dont move一般的想法是将行no - a字符向右移动。要做到这一点,只需添加
System.out.print(new String(new char[no - a]).replace('\0', ' '));在循环开始时,在每一行之前打印no-a空格。
发布于 2013-12-03 16:45:54
在for-each循环之前添加此代码
for(int i=no-a;i>=0;--i){
System.out.print(" ");
}发布于 2013-12-03 16:48:00
对于这个问题,我从未见过如此复杂的解决办法。您还使用了arraylist、Collection类和for每个循环。如果您正在寻找一种更简单的解决方案,下面是一个简单的解决方案:
假设no是输入的号码:
for(int i=1;i<=no;i++){
for(int k=no;k>=i;k--){ System.out.print(' ');}
for(int j=1;j<=i;j++){ System.out.print('%d '),j;}
System.out.println();
}https://stackoverflow.com/questions/20356537
复制相似问题