gpt4 book ai didi

java - 如何每 8 个输入创建一个新行

转载 作者:行者123 更新时间:2023-12-01 19:34:48 24 4
gpt4 key购买 nike

我的代码要求我创建一个数组(根据用户输入),向后显示它,并找到每个数字的总和。到目前为止,我已经能够完成所有要求。但是,如果数组超过 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 语句内部应该包含哪些内容?

输出应该是这样的:

How many elements in the array? 20

Please enter the next value 1

Please enter the next value 2

Please enter the next value 3

Please enter the next value 4

Please enter the next value 5

Please enter the next value 6

Please enter the next value 7

Please enter the next value 8

Please enter the next value 9

Please enter the next value 10

Please enter the next value 11

Please enter the next value 12

Please enter the next value 13

Please enter the next value 14

Please enter the next value 15

Please enter the next value 16

Please enter the next value 17

Please enter the next value 18

Please enter the next value 19

Please enter the next value 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

The Sum of the array's elements is : 210.000

最佳答案

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

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

关于java - 如何每 8 个输入创建一个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58225516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com