如何每8个输入输入一条新行

时间:2019-10-03 19:14:40

标签: java

我的代码要求我创建一个数组(从用户输入),向后显示它,并找到每个数字的总和。到目前为止,我已经能够满足所有要求。但是,如果数组有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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

通常,当您想每 n 次做某事时,您想使用modulo division%

更改此

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

对此

if (j % 8 == 0) // here is where I'm having the problem
{
    System.out.print("\n");
}
相关问题