2014-03-03 2 views
0

자바 프로그램을 작성 중입니다. 프로그램의 입력에 도움이 필요합니다. 즉 하나 이상의 공백으로 구분 된 두 개의 토큰을 포함하는 일련의 줄입니다.빈 줄까지 시퀀스 읽기

import java.util.Scanner; 
class ArrayCustomer { 
public static void main(String[] args) { 
    Customer[] array = new Customer[5]; 
    Scanner aScanner = new Scanner(System.in); 
    int index = readInput(aScanner, array); 
} 
} 

답변

0

이있는 경우 여분의 공백을 제거합니다 value.trim().length()

trim() 방법을 사용하는 것이 좋습니다.

은 또한 String는 당신이 그것을 할당하기 전에 유형 CustomerString 밖으로 객체를 생성해야합니다 Customer에 할당됩니다.

0

다음 코드를 사용하십시오. "stuff.txt"가 현재있는 위치에서 읽을 파일을 넣을 수 있습니다. 이 코드는 String 클래스의 split() 메서드를 사용하여 파일 끝까지 텍스트의 각 줄을 토큰 화합니다. 코드에서 split() 메서드는 공백을 기준으로 각 줄을 나눕니다. 이 메소드는 토큰 화하는 방법을 결정하기 위해이 코드의 빈 공간과 같은 정규식을 사용합니다.

import java.io.*; 
import java.util.ArrayList; 

public class ReadFile { 

static ArrayList<String> AL = new ArrayList<String>(); 

public static void main(String[] args) { 
    try { 
    BufferedReader br = new BufferedReader(new FileReader("stuff.txt")); 
     String datLine; 
     while((datLine = br.readLine()) != null) { 
       AL.add(datLine); // add line of text to ArrayList 

       System.out.println(datLine); //print line 
     } 
     System.out.println("tokenizing..."); 




     //loop through String array 
     for(String x: AL) { 
       //split each line into 2 segments based on the space between them 
       String[] tokens = x.split(" "); 
      //loop through the tokens array 
      for(int j=0; j<tokens.length; j++) { 
        //only print if j is a multiple of two and j+1 is not greater or equal to the length of the tokens array to preven ArrayIndexOutOfBoundsException 
        if (j % 2 ==0 && (j+1) < tokens.length) { 
          System.out.println(tokens[j] + " " + tokens[j+1]); 
        } 
      } 

     } 


} catch(IOException ioe) { 
     System.out.println("this was thrown: " + ioe); 

} 

} 



}