2013-04-25 3 views
0

파일에서 읽은 문자열 개체의 배열이 있습니다. 이러한 문자열 중 일부는 int로 사용해야합니다. 내가 파일을 읽을 수있는 방법을 썼습니다하지만 지금 난 그냥 파일에서 번호를 얻는 방법을 모르는, 여기에 파일을 여기문자열을 int로 변경

29,, 
Chute,1,0 
Chute,2,0 
Chute,3,0 
Chute,4,0 
Chute,5,0 
Chute,6,0 
Chute,7,0 
Chute,8,0 
Chute,9,0 
Chute,0,1 
Chute,0,2 
Chute,0,3 
Chute,9,1 
Chute,9,2 
Chute,9,3 
Ladder,0,5 
Ladder,1,5 
Ladder,2,5 
Ladder,3,5 
Ladder,4,5 
Ladder,5,5 
Ladder,6,5 
Ladder,7,5 
Ladder,8,5 
Ladder,9,5 
Ladder,9,6 

것은 나의 방법이다

public void readBoard(String file)throws FileNotFoundException 
{ 
    File clboard = new File ("myBoard.csv"); 
    Scanner x = new Scanner(clboard); 
    while(x.hasNext()) 
    { 
     String c = x.nextLine(); 
     String [] myboard =c.split(","); 
    } 
} 
+0

전용 CSV 라이브러리를 사용하십시오. [OpenCSV] (http://opencsv.sourceforge.net/)에서 파일을 읽습니다. CSV 파일을 처리 할 때'split' 메서드가 약간 이상하게 사용됩니다. 예를 들어 마지막 요소가 비어 있으면 잘못 처리됩니다. 문자열을 int로 변환하려면,'Integer.parseInt (str)'을 사용하십시오. –

답변

0
String [] myboard = c.split(","); 
if (myboard.length < 3) { 
    // error message 
} else { 
    int i1 = Integer.parseInt(myboard[1]); 
    int i2 = Integer.parseInt(myboard[2]); 
} 

NumberFormatException (숫자가 아닌 것을 변환하려고 할 때 발생)을 처리하기 위해 try/catch를 추가 할 수도 있습니다.

1

split 라인 직후

int numOne = Integer.parseInt(myboard[1]); 
int numTwo = Integer.parseInt(myboard[2]); 

을보십시오.

0
public void readBoard(String file)throws FileNotFoundException 
{ 
    File clboard = new File ("myBoard.csv"); 
    Scanner x = new Scanner(clboard); 
    while(x.hasNext()) { 
     List<Integer> number = new ArrayList<Integer>(); 
     String c = x.nextLine(); 
     String [] myboard =c.split(","); 
     for (String candid8 : myboard) { 
      try { 
       number.add(Integer.parseInt(candid8)); 
      } catch (NumberFormatException e) { 
      } 
     } 
    } 
} 

숫자는 이제 목록입니다. 더 복잡한 문법 인 경우 jflex을 살펴보세요. Google의 추천 인 것으로 보입니다.