【发布时间】:2017-11-24 00:44:38
【问题描述】:
我有一个看起来无法解决的小问题:
目标:通过向单个空白字符添加空格来对齐 ArrayList 中的行(字符串),以使文本对齐。
package com.mycompany.app;
导入 java.util.ArrayList; 导入 java.util.List;
公共类 MaxLengthLine {
String[] words;
int size;
int qtySpaces;
public MaxLengthLine (String text, int size){
this.words = text.split(" ");
this.size = size;
}
List<String> lines = new ArrayList<String>();
public void lineResize() {
int index = 0;
for (int i = 0; i < words.length - index; i++){
String curLine = "";
while((curLine + words[index]).length() <= size){
curLine += words[index] + " ";
index++;
}
curLine = curLine.substring(0, curLine.length()-1);
lines.add(curLine);
}
String curLine = "";
while(index < words.length){
curLine += words[index] + " ";
index++;
}
curLine = curLine.substring(0, curLine.length()-1);
lines.add(curLine);
}
public void lineJustify() {
for (int i = 0; i < lines.size(); i++){
while (lines.get(i).length() < size){
String test = lines.get(i).replaceFirst(" ", " ");
lines.set(i, test);
}
}
}
public String getTextFull (){
String output = "";
for(int i = 0; i < lines.size();i++){
output += lines.get(i) + "\n";
}
while (output.contains(" ")){
output = output.replace(" ", " ");
}
return output;
}
}
这段代码是我一开始想到的最直接的解决方案(除了我已经尝试了很多其他的),但由于某种原因,结果一直是一样的。
实际输出:
In the beginning God created the heavens
and the earth. Now the earth was
formless and empty, darkness was over
the surface of the deep, and the Spirit
of God was hovering over the waters.
And God said, "Let there be light," and
there was light. God saw that the light
was good, and he separated the light
from the darkness. God called the light
"day," and the darkness he called
"night." And there was evening, and
there was morning - the first day.
期望的输出:
In the beginning God created the heavens
and the earth. Now the earth was
formless and empty, darkness was over
the surface of the deep, and the Spirit
of God was hovering over the waters.
And God said, "Let there be light," and
there was light. God saw that the light
was good, and he separated the light
from the darkness. God called the light
"day," and the darkness he called
"night." And there was evening, and
there was morning - the first day.
编辑:输入:
起初神创造天地。现在地是空虚混沌,渊面黑暗,神的灵运行在水面上。 上帝说:“要有光”,于是就有了光。神看光是好的,就把光暗分开了。上帝称光为“白天”,称黑暗为“黑夜”。有晚上,有早晨——第一天。
(我已经有代码可以在 40 个字符处正确断行而不会断词,所以最后一部分是将文本对齐为 40 个字符的函数)
编辑 2:我将整个班级的那段代码更改为更清晰,我的 teste 上设置的大小是 40。
【问题讨论】:
-
还有...示例输入?
-
没有什么可以证明的——首先你想要达到的宽度在哪里?
-
你在哪里计算变量
size? -
对不起,编辑了更多信息,如果需要我可以粘贴整个课程,我只是认为没有必要
-
为什么这看起来“无法解决”?如果你能用手做,你可以用代码来做。
标签: java