FirmView
FirmView

Reputation: 3150

Formating string and writing to a file in java

I have some strings which are to be formated and write to a file,

Sample strings,

text1
text2
text3
text4
text5
text6
text7
text8
text9
text10
text11
text12
text13

The first 10 lines should come in first column and the remaining lines should come in 2nd column. from 1st column to second column there should be a space of 30

This is what i tried,

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

I have attached an image of expected output.

enter image description here

Upvotes: 0

Views: 111

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136032

try

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

output

text1                        text11
text2                        text12
text3                        text13
text4                              
text5                              
text6                              
text7                              
text8                              
text9                              
text10         

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

Your loop needs to go for ten iterations (one per line), not fifteen (one per word). At each iteration, you have to consider two numbers:

  • Line number, and
  • Line number plus ten

The first number always gets printed; the second number gets printed along with the first only if the second number is fifteen or less:

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

Upvotes: 2

Related Questions