简体   繁体   English

倒三角形的数字

[英]Upside-down triangle of numbers

I'm a beginner to Java and can't figure out how to print an upside down triangle of numbers.我是 Java 的初学者,不知道如何打印一个倒三角形的数字。 The numbers should decrease in value by 1 for each row.每行的数字值应减少 1。 Ex.前任。 Number of rows: 6 ;行数: 6

Print:打印:

666666
55555
4444
333
22
1

So far this is what I came up with;到目前为止,这是我想出的; ( int nr is scanned input from user) int nr是来自用户的扫描输入)

for (int i = 1; i <= nr; i++) {
    for (int j = 1; j <= nr; j++) {
        System.out.print(nr);
    }
    nr--;
    System.out.println();
}

By having nr--;通过拥有nr--; the loop gets shorter and I cant figure out how to keep the loop going for nr -times, yet still decreasing the amount of numbers printed out.循环变短了,我不知道如何让循环持续nr ,但仍然减少打印出的数字量。

You are right in that you need to write a loop to print a line for each number, starting at nr and decreasing by 1 until you get to 0. But you also have to print a variable number of numbers at each line.您是对的,因为您需要编写一个循环来为每个数字打印一行,从 nr 开始并减少 1 直到达到 0。但是您还必须在每行打印可变数量的数字。 To do that, a nested loop could be used to print the number the amount of times necessary.为此,可以使用嵌套循环来打印所需次数的数字。

Since you start printing at nr and decrease until you reach 1, you could try writing an outer loop that decrements rather than increments.由于您从 nr 开始打印并减少直到达到 1,您可以尝试编写一个递减而不是递增的外部循环。 Then use a nested loop to print the number the required number of times.然后使用嵌套循环打印所需次数的数字。 For example:例如:

for (int i = nr; i > 0; i--) {
    for (int j = 0; j < i; j++) {
        System.out.print(i);
    }
    System.out.println();
}

In this case, you can use a single while loop and two decreasing variables:在这种情况下,您可以使用单个while 循环和两个递减变量:

  • i - number of the row - from 6 to 1 i - 行号 - 从61
  • j - number of repetitions in the row - from i to 1 : j - 行中的重复次数 - 从i1
int i = 6, j = i;
while (i > 0) {
    if (j > 0) {
        // print 'i' element 'j' times
        System.out.print(i);
        --j;
    } else {
        // start new line
        System.out.println();
        j = --i;
    }
}

Output:输出:

666666
55555
4444
333
22
1

See also: Printing a squares triangle.另请参阅:打印正方形三角形。 How to mirror numbers?如何镜像数字?

Your problem is that you are changing nr , try:您的问题是您正在更改nr ,请尝试:

int original_nr = nr;
for (int i = 1; i <= original_nr; i++) {
    for (int j = 1; j <= nr; j++) {
        System.out.print(nr);
    }
    nr--;
    System.out.println();
}

You can't decrease nr and still use it as upper limit in the loops.您不能减少nr并仍将其用作循环中的上限。 You should in fact consider nr to be immutable .实际上,您应该将nr视为不可变的

Instead, change outer loop to count from nr down to 1 , and inner loop to count from 1 to i , and print value of i .相反,将外循环更改为从nr向下计数到1 ,将内循环更改为从1计数到i ,并打印i值。

for (int i = nr; i > 0; i--) {
    for (int j = 0; j < i; j++) {
        System.out.print(i);
    }
    System.out.println();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM