首页 > 解决方案 > 如何每 8 个输入创建一个新行

问题描述

我的代码要求我创建一个数组(从用户输入),向后显示它,并找到每个数字的总和。到目前为止,我已经能够完成所有要求。但是,如果数组超过 8 个数字,那么当它显示时,程序必须每隔 8 个数字创建一个新行。我很难实现这个目标。到目前为止,这是我的代码:

import java.util.Scanner;

public class arrayCreator {

    public static void main(String[] args) {

        int length;
        double sumArray = 0;

        Scanner input = new Scanner(System.in);
        System.out.print("How many elements in the array? ");
        length = input.nextInt();

        }

        for(int j = currentArray.length-1; j >= 0; j-- )
        {
            System.out.printf("%.3f \t", currentArray[j]);

            if(currentArray.length - 8 == j) // here is where I'm having the problem
            {
                System.out.print("\n");
            }


        input.close();
    }

}

为了在每次显示 8 个输入时创建一个新行,if 语句中应该包含什么内容?

这就是输出的样子:

数组中有多少个元素?20

请输入下一个值 1

请输入下一个值 2

请输入下一个值 3

请输入下一个值 4

请输入下一个值 5

请输入下一个值 6

请输入下一个值 7

请输入下一个值 8

请输入下一个值 9

请输入下一个值 10

请输入下一个值 11

请输入下一个值 12

请输入下一个值 13

请输入下一个值 14

请输入下一个值 15

请输入下一个值 16

请输入下一个值 17

请输入下一个值 18

请输入下一个值 19

请输入下一个值 20

20.000 19.000 18.000 17.000 16.000 15.000 14.000 13.000
12.000 11.000 10.000 9.000 8.000 7.000 6.000 5.000
4.000 3.000 2.000 1.000

数组元素的总和是:210.000

标签: java

解决方案


另一个答案无法正常工作,因为您正在从列表的末尾备份到开头,但是 mod 运算符会导致换行,就好像您从开头移动到结尾一样。但是,使用模运算符的想法绝对是正确的。在您的 if 语句中执行此操作:

if((length - j) % 8 == 0) {
    System.out.print("\n");
}

推荐阅读