Nice guy
Nice guy

Reputation: 13

How to split strings into columns

I have a list of Strings in single column. I want to make three columns from these string and then print the ouput to another file. How do I do this?

Here is what I've tried so far:

ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");

try {
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(line);
    }

    scanner.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

My input data:

City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr

My expected output:

City      Gsk      Relocation
sripallu here      jrajesh
gurgaon  unitech   StatisticsThreads
WizOty   LTDParsvnathK  Quotesby
newest   PMaashuktr      Loans
.
.
.
.
.
.
.

Upvotes: 1

Views: 1829

Answers (2)

Radu Murzea
Radu Murzea

Reputation: 10920

I took your code and modified it a little:

File file = new File("f://file.txt");

try {
    Scanner scanner = new Scanner(file);

    int itemsOnRow = 0;

    while (scanner.hasNextLine()) 
    {
        String line = scanner.nextLine();
        System.out.print (line + " ");

        itemsOnRow++;

        if (itemsOnRow == 3)
        {
            itemsOnRow = 0;
            System.out.println ();
        }
    }

    scanner.close();
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}

You should actually try to implement it next time. If you fail but post the code that you wrote, then it's easier for the people here to help you.

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

You can structured your requirement in class like Output and make a list of Output.

public class Output{
   private String str1;
   private String str2;
   private String str3;
   <geter & setter method>
}

...

ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
     String line = scanner.nextLine();i = ++i%3;
     if(i==0){
        op = new Output();
        op.setStr1(line);
     }else if(i==1)
        op.setStr2(line);
     else
        op.setStr3(line);
}

Upvotes: 1

Related Questions