java - 如何使用 println 按单位打印同一列中的数字列表?
问题描述
我承认这是一个愚蠢的问题,但它只是我无法解决的大型计算项目的一小部分。为了打破它,我想在新行上打印我的数组值。
为了美观,我需要将我的值的单位放在同一列中......所以当我编码时会出现这种情况:
1
2
3
10
111
0
我的代码:
public void display() {
int j;
System.out.println(name);
for (j = 0; j < treesOfForest.length; j++) {
if (treesOfForest[j] != null) {
System.out.print(" ");
System.out.printf("%d",(j+1));
System.out.println( " : " + treesOfForest[j]);
}
}
}
我的预期输出:
解决方案
如果您只想实现间距,一种选择是使用String#format
:
int[] treesOfForest = new int[] {1, 2, 3, 10, 111, 0};
for (int j=0; j < treesOfForest.length; j++) {
System.out.println(String.format("%3d", treesOfForest[j]));
}
1
2
3
10
111
0
推荐阅读
- php - How to find out the values from a specific column in the results of a MySQL query?
- elasticsearch - 如何在 kibana 数据表中添加多个案例条件
- c# - 我正在尝试使用鼠标拖动元素,但它总是从特定位置而不是当前位置开始拖动
- discord.js - Bot mention as a prefix in Discord.js
- c# - C# How to connect to different databases based on a flag
- javascript - Using external JS libraries in a web component
- qnx - QNX momentics linked source files not compiling
- azure - 如何在 Azure Windows Server 虚拟机中使用我的网络摄像头?
- angularjs - AngularJS - ng-model 没有正确更新
- cmake - add_custom_target 列表提供的多个依赖项