java怎么实现一行两列_有没有一种简单的方法将两列输出到Java中的控制台?

回答得晚了,但是如果你不想硬编码宽度,那么这样的功能如何:

public static void main(String[] args) {

new Columns()

.addLine("One", "Two", "Three", "Four")

.addLine("1", "2", "3", "4")

.print()

;

}

并显示:

One Two Three Four

1 2 3 4

好吧,只需要:

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Columns {

List> lines = new ArrayList<>();

List maxLengths = new ArrayList<>();

int numColumns = -1;

public Columns addLine(String... line) {

if (numColumns == -1){

numColumns = line.length;

for(int column = 0; column < numColumns; column++) {

maxLengths.add(0);

}

}

if (numColumns != line.length) {

throw new IllegalArgumentException();

}

for(int column = 0; column < numColumns; column++) {

int length = Math

.max(

maxLengths.get(column),

line[column].length()

)

;

maxLengths.set( column, length );

}

lines.add( Arrays.asList(line) );

return this;

}

public void print(){

System.out.println( toString() );

}

public String toString(){

String result = "";

for(List line : lines) {

for(int i = 0; i < numColumns; i++) {

result += pad( line.get(i), maxLengths.get(i) + 1 );

}

result += System.lineSeparator();

}

return result;

}

private String pad(String word, int newLength){

while (word.length() < newLength) {

word += " ";

}

return word;

}

}

因为它只有所有的行才能打印,所以它可以了解列的宽度。不需要硬编码宽度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值