2013-01-19 185 views
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

你打算如何分割列?什麼是分隔符? – Swapnil

+1

輸出的分隔符​​或分隔符的分隔符? –

+3

'我的代碼我試過'我看不到任何邏輯在這裏拆分列。這不是一個嘗試! –

回答

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

下次應該嘗試實施它。如果你失敗了,但是發佈了你寫的代碼,那麼這裏的人可以更容易地幫助你。

+0

寫不好的代碼是不需要的只是給他很好的建議做什麼。 –