0

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

示例字符串,

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

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

在此处输入图像描述

4

2 回答 2

2

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

  • 行号,和
  • 行号加十

第一个数字总是被打印出来;仅当第二个数字为 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");
    }    
}
于 2013-01-08T03:22:07.987 回答
0

尝试

    for (int i = 1; i <= 10; i++) {
        String text1 = "text" + i;
        String text2 = i <= 3 ? "text" + (i + 10) : "";
        System.out.printf("%s%30s\n", text1, text2);
    }

输出

text1                        text11
text2                        text12
text3                        text13
text4                              
text5                              
text6                              
text7                              
text8                              
text9                              
text10         
于 2013-01-08T04:53:31.423 回答