2013-01-19 5 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

나쁜 코드를 작성하지 않아도 그냥 그에게 좋은 제안을 줘. –

관련 문제