java - 如何每 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
解决方案
另一个答案无法正常工作,因为您正在从列表的末尾备份到开头,但是 mod 运算符会导致换行,就好像您从开头移动到结尾一样。但是,使用模运算符的想法绝对是正确的。在您的 if 语句中执行此操作:
if((length - j) % 8 == 0) {
System.out.print("\n");
}
推荐阅读
- google-earth-engine - Google Earth Engine 视频导出错误(a.element.map 不是函数)
- c++ - 编译器没有完成进程
- javascript - 在向子组件获取请求后发出传递道具(React)
- node.js - Heroku Nodejs应用程序启动后崩溃
- javascript - 如何在多次打开不同的模式窗口后停止多个 jQuery Ajax 调用
- for-loop - 如何根据条件更改 for 循环
- javascript - switch-case 中的逻辑“case”语法,jsx
- mongodb - 尝试通过 Consul Connect Sidecar Proxy 连接到 mongodb 服务
- python - Pandas merge_asof:不兼容的合并键 [datetime64[ns, US/Eastern] 和 dtype('
我有两个由某人创建的数据框,我需要在和上进行merge_asof。左
- ruby - 我不断收到一个我不明白的错误