0

我正在用数字编写这个程序,但我被困住了,需要一些帮助。

到目前为止的代码:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Oppgi øvre grense: ");
    int Number = in.nextInt(); 
    int tall = 1;
    for(int t = 0; tall <=45; tall++){
            System.out.println(" " + tall);
    }   
}

目标:让第一行包含一个数字,第二行包含两个数字,第三行包含三个数字,等等。输出应该看起来像一个金字塔,每行数字之间的间距不同。

如果有人可以帮助我解决解决方案代码。谢谢你。

总产量:45 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 48 39 40 45 24

4

3 回答 3

3
outer loop{
    decides number of numbers in one line
    inner loop{
        prints actual numbers.
        Please keep track of the numbers you have printed so far
        Inner loop starts at numbers printed so far
        It will have passes = number of numbers to print
    }
}  

您在这里有两个不同的任务:
1. 决定在一行中打印多少个数字
2. 实际打印数字

既然是这样,一个循环决定要打印多少个数字:外循环。它是外循环的原因是因为您需要清楚地了解在实际打印之前需要打印多少个数字。
另一个循环:内部循环执行实际打印。

所以,一旦你从外循环开始,你的内循环就会开始打印。
然后它将查看是否打印了该通行证的最大数量。
如果是,请停止。然后,增加外循环。回来,打印,检查,然后做同样的事情。

够容易吗?

于 2013-10-21T15:09:18.950 回答
0
public class RareMile {

    public static void main (String[] args){
        printNum(5);
    }

    public static void printNum (int n){
        int k=1, sum=0;
        for (int i=1; i<=n; i++){
            sum=0;
            for(int j=1; j<=i; j++){    
                System.out.print(k);
                sum = sum+k;
                k++;                
                }
            System.out.print("            =" + sum);
            System.out.println();
        }        
    }

}

真正的问题是如何只用一个 for 循环来做到这一点?

于 2014-02-07T14:03:26.803 回答
-1

跟踪行号,例如

int line = 1; // line number
int count = 0; // number of numbers on the line
for(int x = 0; x <= 45; x++){
    if (count == line){
        System.out.println(""); // move to a new line
        count = 0; // set count back to 0
        line++; // increment the line number by 1
    }
    System.out.print(x); // keep on printing on the same line
    System.out.print(" "); // add a space after you printed your number
    count++;
}
于 2013-10-21T15:20:42.953 回答