1

我在单列中有一个字符串列表。我想从这些字符串中创建三列,然后将输出打印到另一个文件。我该怎么做呢?

这是我迄今为止尝试过的:

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

我的输入数据:

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

我的预期输出:

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

2 回答 2

1

您可以在类中构建您的需求,如输出并制作输出列表。

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);
}
于 2013-01-19T11:46:05.250 回答
0

我拿了你的代码并做了一些修改:

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

您实际上应该尝试下一次实施它。如果你失败了但发布了你写的代码,那么这里的人更容易帮助你。

于 2013-01-19T11:42:53.390 回答