我有一些字符串需要格式化并写入文件,
示例字符串,
text1
text2
text3
text4
text5
text6
text7
text8
text9
text10
text11
text12
text13
前 10 行应位于第一列,其余行应位于第二列。从第一列到第二列应该有 30 的空格
这是我尝试过的
File f = new File("sample.txt");
FileWriter fw = new FileWriter(f);
pw = new PrintWriter(fw);
String text;
for(int i=0; i<15; i++){
text = "text" + i;
if(i <= 10){
pw.format(text + "\n");
} else{
pw.format("%30s",text + "\n");
}
}
}
我已附上预期输出的图像。
最佳答案
您的循环需要进行十次迭代(每行一次),而不是十五次(每个单词一次)。在每次迭代中,您必须考虑两个数字:
- 行号,以及
- 行号加十
始终打印第一个数字;仅当第二个数字等于或小于 15 时,第二个数字才会与第一个数字一起打印:
for(int i=0; i != 10 ; i++) {
String text1 = "text" + i;
String text2 = "text" + (i+10);
if(i <= 5){
pw.format("%s%30s\n",text1, text2);
} else {
pw.format(text + "\n");
}
}
关于java - 在java中格式化字符串并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14207693/