该程序应该要求用户输出最大数量,然后计算从1到最大值的每个数字以及它的平方

时间:2017-11-22 08:02:57

标签: java

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Please enter the max number:");

    int max = input.nextInt();

    int[]arr1 = new int[max+1];
    int[]arr2 = new int[max+1];
    int[]arr3 = new int[max+1];

    int i = 1;

    // For-loop to calculate 
    for (i = 1;i <= max;i++)
        arr1[i] = arr1[i-1] + i;

    i = 1;

    // While-loop to calculate
    while (i <= max) {
        arr2[i] = arr2[i-1] + i;
        i++;
    }

    i = 1;

    // Do-While-loop to calculate
    do
        arr3[i] = arr3[i-1] + i;
    while (++i <= max);

    for (i = 0; i <= max; i++)
        System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);

    System.out.println("Sum of All is " + arr1[max]);

}

我有这个用于做总结,但是当我遇到它时,我感到困惑

1 个答案:

答案 0 :(得分:0)

您似乎有3个相同的array个对象?

无论如何,打印从1到max的所有数字的正方形非常简单:

for (int i = 1; i <= max; i++) {
    System.out.println(i + ": " + i * i);
}

还有一些有趣的方法可以将数字从1加到max,例如:

System.out.println(IntStream.range(1, max + 1).sum());