从数组元素打印半金字塔

Printing a half pyramid from array elements

我是 Java 的新手,刚开始学习它。我有一个数字数组,数组长度为 origArraySize:

29.50   10.80   16.40   87.80   12.20   63.70   13.90   25.00   77.40   97.40

我正在尝试以这种格式排列它们:

29.50
10.80   16.40
87.80   12.20   63.70
13.90   25.00   77.40   97.40

虽然我见过类似的半金字塔问题,但我似乎无法弄清楚如何实现一个数组来打印数字。这是我到目前为止得到的,只是 class rn:

的一种方法
public String toString() {
    String t = "";
    for (int i = 0; i < this.origArraySize; i++) {
        t += String.format("%8.2f", array[i]);
        for (int j = 0; j < i; j++) {
            System.out.println(t + "\n");
        }
    }
}

我知道它包含嵌套的 for 循环,但我似乎无法理解。 toString() 方法必须 return String 值,我也不确定最后如何实现它,但现在我尝试使用 t.

您不需要内部循环,您只需要几个计数器

double arr[] = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};

int loop = 0;
int printAtNum = 0;

for (double d : arr) {
    System.out.printf("%8.2f", d); // always print
    if (loop == printAtNum) {
        System.out.println(); // only print if loop is equal
                              // to incremented counter
        loop = 0;       // reset
        printAtNum++;   // increment
    } else {
        loop++;
    }
}

输出

   29.50
   10.80   16.40
   87.80   12.20   63.70
   13.90   25.00   77.40   97.40

您可以使用两个嵌套的 for 循环。内部操作是打印并递增单个值:

public static void main(String[] args) {
    double[] arr = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};
    printHalfPyramid(arr);
}
public static void printHalfPyramid(double[] arr) {
    int i = 0; // counter, index of an element in an array
    for (int row = 1; row < Integer.MAX_VALUE; row++) {
        for (int el = 0; el < row; el++) {
            // print a number and increment a counter
            System.out.print(arr[i++] + " ");
            // if the last element
            if (i == arr.length) return;
        }
        // line break, next row
        System.out.println();
    }
}

输出:

29.5 
10.8 16.4 
87.8 12.2 63.7 
13.9 25.0 77.4 97.4