を空白ために空白を追加:Javaは、私は解決不可能に見える小さな問題持って
GOAL:正当取得するには、単一の空白文字に空白を追加することによって、ArrayListの中にテキストのために必要なだけの行(文字列)を揃えを。
package com.mycompany.app;
import java.util.ArrayList; import 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;
}
}
このコードは、私は(私はすでに他の多くを試みた以外に)最初に考え最もstraightfoward溶液であるが、何らかの理由で結果が来続けます同じ。
実際の出力:
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文字で正確にラインを壊しコードを持っている)
EDIT 2:私は、コードのその部分を変更クラス全体より明確にするために、私の精巣に設定されているサイズは、JavaのStringクラスから40
そして...例えば、入力? – alfasin
何も正当化する必要はありません - あなたが到達しようとしている幅はどこですか? – John3136
変数 'size'はどこで計算されますか? –