2011-02-03 4 views
1

좋은 하루 되세요!Java로 파일 쓰기

내일 아침에 제출해야하는 프로젝트 (게임)가 있습니다. 하지만 고득점을 기록 할 때 버그를 발견했습니다. 텍스트 파일을 만들고 SCORE NAME을 점수를 기준으로 내림차순으로 작성하려고합니다.

예를 들어

:

SCORE NAME   RANK 
230  God 
111  Galaxian  
10  Gorilla 
5  Monkey 
5  Monkey 
5  Monkey 

거기 다음과 같이 내 코드 인 RANK이기도 참고 :

public void addHighScore() throws IOException{ 
     boolean inserted=false; 

     File fScores=new File("highscores.txt"); 
     fScores.createNewFile(); 

     BufferedReader brScores=new BufferedReader(new FileReader(fScores)); 
     ArrayList vScores=new ArrayList(); 
     String sScores=brScores.readLine(); 
     while (sScores!=null){ 
       if (Integer.parseInt(sScores.substring(0, 2).trim()) < score &&  inserted==false){ 
         vScores.add(score+"\t"+player+"\t"+rank); 
         inserted=true; 
       } 
       vScores.add(sScores); 
       sScores=brScores.readLine(); 
     } 
     if (inserted==false){ 
       vScores.add(score+"\t"+player+"\t"+rank); 
       inserted=true; 
     } 
     brScores.close(); 

     BufferedWriter bwScores=new BufferedWriter(new FileWriter(fScores)); 
     for (int i=0; i<vScores.size(); i++){ 
       bwScores.write((String)vScores.get(i), 0, ((String)vScores.get(i)).length()); 
       bwScores.newLine(); 
     } 
     bwScores.flush(); 
     bwScores.close(); 
} 

는하지만 난 입력 세 개의 숫자 경우 : 60 매니이 파일은 다음과 같이 될 것이다 :

60  Manny 
    230  God 
    111  Galaxian  
    10  Gorilla 
    5  Monkey 
    5  Monkey 
    5  Monkey 

문제는를 사용하기 때문에 2 개의 숫자 만 읽을 수 있다는 것입니다.. sScores.substring(0, 3).trim())으로 변경하려고했습니다. 문자 부분까지 읽으므로 오류가 발생합니다. 누구든지 최대 4 개의 숫자를 읽을 수 있도록 내 코드를 수정하는 데 도움을 줄 수 있습니까? 귀하의 도움을 매우 높이 평가 될 것입니다.

답변

3

당신이 사용해야하는 것은 :

String[] parts = sScrores.trim().split("\\s+", 2); 

그런 다음 당신이 1

int theNumber = Integer.parseInt(parts[0].trim(); 
String theName = parts[1].trim(); 

당신은 다시 쓸 수 인덱스에서 인덱스 0의 수에 배열하고, 이름이됩니다 반면 루프과 같이 : 개인적으로

String sScores=brScores.readLine().trim(); 
while (sScores!=null){ 
     String[] parts = sScrores.trim().split(" +"); 
     int theNumber = Integer.parseInt(parts[0].trim(); 
     if (theNumber < score &&  inserted==false){ 
       vScores.add(score+"\t"+player+"\t"+rank); 
       inserted=true; 
     } 
     vScores.add(sScores); 
     sScores=brScores.readLine(); 
} 

, 나는 구문 분석에 도움이되는 새로운 HighScore 클래스를 추가합니다 파일.

class HighScore { 

    public final int score; 
    public final String name; 
    private HighScore(int scoreP, int nameP) { 
     score = scoreP; 
     name = nameP; 
    } 

    public String toString() { 
     return score + " " + name; 
    } 

    public static HighScore fromLine(String line) { 
     String[] parts = line.split(" +"); 
     return new HighScore(Integer.parseInt(parts[0].trim()), parts[1].trim()); 
    } 
} 
+0

같은 글을 쓰고 있었다 : P – jjczopek

+0

@jjc, 네가 옳았다. – jjnguy

+0

그'.split ("+")' –

2

각 줄의 형식은 항상 동일하며 정수, 그 다음에 탭, 플레이어 이름이옵니다.

점수를 구문 분석하기 전에 각 줄에서 탭 문자의 색인을 찾아서이 색인에 포함되지 않은 부분 문자열 (0을 포함)을 찾습니다.

플레이어 이름은 탭 인덱스 +1에서 행의 길이를 초과하는 부분 문자열을 가져 와서 얻을 수 있습니다.

+0

이것은 또한 좋은 해결책입니다. – jjnguy

+0

하나님, 나는 배울 것이 많습니다! 감사. :) – newbie

1

위의 표가 파일 인 경우.

첫 번째 두 점수는 괜찮을 것이지만 5는 문자 읽기를 시작합니다. 그것이 문제의 원인 일 수 있습니다.

+0

도 감사합니다 :) – newbie