实现说明
把文本两端对齐到固定宽度可以归结为类 ParagraphJustify和函数 justify、main。
文件的主干是一个循环——while (i < words.size())。
使用要点
- 运行整个文件:
main会依次驱动justify。
常见问题
「把文本两端对齐到固定宽度」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
主要签名是 static List<String> justify(List<String> words, int width)
核心语句
len += 1 + words.get(j).length();
代码示例
import java.util.ArrayList;
import java.util.List;
public class ParagraphJustify {
// 两端对齐(full justify):剩余空格均摊到行内所有词隙;
// 最后一行或单行不做拉伸,用普通空格连接
static List<String> justify(List<String> words, int width) {
List<String> lines = new ArrayList<>();
int i = 0;
while (i < words.size()) {
int len = words.get(i).length();
int j = i + 1;
while (j < words.size() && len + 1 + words.get(j).length() <= width) {
len += 1 + words.get(j).length();
j++;
}
StringBuilder line = new StringBuilder(words.get(i));
if (j == words.size() || j - i == 1) {
for (int k = i + 1; k < j; k++) {
line.append(' ').append(words.get(k));
}
} else {
int gaps = j - i - 1;
int spaces = (width - len) + gaps; // 每个词隙保底 1 个 + 待分配
int base = spaces / gaps;
int extra = spaces % gaps;
for (int k = i + 1; k < j; k++) {
for (int s = 0; s < base + (k - i <= extra ? 1 : 0); s++) {
line.append(' ');
}
line.append(words.get(k));
}
}
lines.add(line.toString());
i = j;
}
return lines;
}
public static void main(String[] args) {
List<String> words = List.of("Packaging", "decisions", "must", "be", "made",
"with", "real", "size", "budgets", "not", "guesses");
for (String line : justify(words, 20)) {
System.out.println("|" + line + "|");
}
}
}