gpt4 book ai didi

java - 在java中格式化字符串并写入文件

转载 作者:行者123 更新时间:2023-12-02 07:21:10 25 4
gpt4 key购买 nike

我有一些字符串需要格式化并写入文件,

示例字符串,

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");
}
}
}

我已附上预期输出的图像。

enter image description here

最佳答案

您的循环需要进行十次迭代(每行一次),而不是十五次(每个单词一次)。在每次迭代中,您必须考虑两个数字:

  • 行号,以及
  • 行号加十

始终打印第一个数字;仅当第二个数字等于或小于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com