Java 如何将字符串拆分为列

Java 如何将字符串拆分为列,java,Java,我有一个单列字符串列表。我想从这些字符串中生成三列,然后将输出打印到另一个文件中。我该怎么做 以下是我到目前为止所做的尝试: ArrayList<String> list=new ArrayList<String>(); File file = new File("f://file.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) {

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

以下是我到目前为止所做的尝试:

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      Loans
.
.
.
.
.
.
.

我接受了您的代码并对其进行了一些修改:

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

下次你应该尝试实现它。如果你失败了,但是发布了你编写的代码,那么这里的人就更容易帮助你了。

我把你的代码修改了一点:

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

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

您可以像输出一样在类中结构化您的需求,并列出输出

public class Output{
   private String str1;
   private String str2;
   private String str3;
   <geter & setter method>
}
公共类输出{
私有字符串str1;
私有字符串str2;
私有字符串str3;
}

ArrayList list=new ArrayList();
int i=-1;输出op=null;
while(scanner.hasNextLine()){
字符串行=scanner.nextLine();i=++i%3;
如果(i==0){
op=新输出();
op.setStr1(行);
}else如果(i==1)
op.setStr2(行);
其他的
op.setStr3(行);
}

您可以像输出一样在类中结构化您的需求,并列出输出

public class Output{
   private String str1;
   private String str2;
   private String str3;
   <geter & setter method>
}
公共类输出{
私有字符串str1;
私有字符串str2;
私有字符串str3;
}

ArrayList list=new ArrayList();
int i=-1;输出op=null;
while(scanner.hasNextLine()){
字符串行=scanner.nextLine();i=++i%3;
如果(i==0){
op=新输出();
op.setStr1(行);
}else如果(i==1)
op.setStr2(行);
其他的
op.setStr3(行);
}

您计划如何拆分列?分隔符是什么?用于拆分的分隔符还是用于输出的分隔符?
我的代码我尝试了什么
我在这里看不到任何用于拆分列的逻辑。这不是一次尝试@NarendraPathai OP说,拆分只需要一列,你不能仅仅发布一些甚至不算一次尝试的代码就可以成功!您计划如何拆分列?分隔符是什么?用于拆分的分隔符还是用于输出的分隔符?
我的代码我尝试了什么
我在这里看不到任何用于拆分列的逻辑。这不是一次尝试@NarendraPathai OP说,拆分只需要一列,你不能仅仅发布一些甚至不算一次尝试的代码就可以成功!不需要写坏代码,只要给他好的建议就行了。不需要写坏代码,只要给他好的建议就行了。