2016-05-21 5 views
0
private int score = 0; 
private int highScore = 0; 


    private void gameOver(Graphics g) { 

     try{ 
       PrintWriter writer = new PrintWriter(new FileWriter("C:\\Users\\Videvik\\workspace\\madu\\logi1.txt", true)); 
       writer.println(score);    
       writer.close(); 
       } catch(Exception ex){ex.printStackTrace();}//creates .txt file 

      File file = new File("logi1.txt"); 

      try { 
       BufferedReader reader = new BufferedReader(new FileReader(file)); 
       String line = reader.readLine(); 
       while (line != null)     // read the score file line by line 
       { 
        try { 
         int score2 = Integer.parseInt(line.trim()); // parse each line as an int 
         if (score2 > highScore)      // and keep track of the largest 
         { 
          highScore = score; 
         } 
        } catch (NumberFormatException e1) { 
         // ignore invalid scores 
         //System.err.println("ignoring invalid score: " + line); 
        } 
        line = reader.readLine(); 
       } 
       reader.close(); 

      } catch (IOException ex) { 
       System.err.println("ERROR reading scores from file"); 


     String msg = "Game over!";//works 
     String msg2 = "Points: "+score;//works 
     String msg3 = "MaxPoints: "+highScore;//does not work 

     Font small = new Font("Helvetica", Font.BOLD, 14); 
     FontMetrics metr = getFontMetrics(small); 

     g.setColor(Color.red); 
     g.setFont(small); 
     g.drawString(msg, (B_WIDTH - metr.stringWidth(msg))/2, B_HEIGHT/2); 
     g.drawString(msg2, (B_WIDTH - metr.stringWidth(msg2))/4, B_HEIGHT/4); 
     g.drawString(msg3, (B_WIDTH - metr.stringWidth(msg3))/6, B_HEIGHT/6); 


      } 

    } 

まあ私の問題は、.txtファイルから最大スコアを画面に表示できないことです。最初のプログラムは、すべてのスコアが保存される.txtファイルを作成します(動作します)。それ以降の2番目の関数は、そこから最も高いスコアを見つけ出し、それを引き出す(動作しない)べきです(「Points」と「Game Over!」を抜き出しています)。何が間違っていますか?スネークゲームのハイスコアを.txtファイルから取得する

一つのパスは絶対的であり、他は相対的である:私は潜在的なエラーがこれら二つのだと思います笑

+2

コードの関連部分のみを表示してください。質問にこのような行が多く含まれている場合はかなり難しいです。質問をより簡潔にするために編集を検討してください –

+0

はい、私のせいで、私は重要でない部分を取り除きました。 – Hidalgo

答えて

0

を私は次水曜日のためにこの事を解決するために持っているか、私は試験に失敗します。 FileWriterはFileをパラメータとして受け入れていますので、なぜあなたの "ファイル"をリーダーとライターの両方に使用しないのですか?あなたが同じ場所を指していることを確認します。

ハイスコアが実際にどこかで更新されているか調べてください。また、そうでない場合は、変更する必要があるだろうハイスコアとして0を表示することはありません:

if(highscore2 > highscore) 

if(highscore2 >= highscore) 

に役立ちます願っています!

+0

ありがとうございました。私の問題を解決しました。また、そのコードの他の問題は、 "スコア2"であり、それはちょうど "スコア"であると考えられていました。 – Hidalgo

関連する問題