如何按特定顺序从序列化的文件中打印某些内容?

时间:2017-05-13 19:30:00

标签: java

所以我只是在做这个小游戏,一切正常,只是我的得分课给我带来了麻烦。所以我想打印出这样的列表 ex ...(我把它带到了胜利的地方。)

1:John Wins:2次抽奖:1次失败:2次

2:乔赢了:1平局:2输了:1

3:客队胜利:0平局:0输掉:0

4:客人赢:0平局:0输:0

问题在于,当我重新读取文件时,它只打印出这样的新名称:

1:亚当获胜:2次平局:1次输球:2次

2:客人赢:0平局:0输:0

3:客队胜利:0平局:0输掉:0

4:客人赢:0平局:0输:0

尽管如此,它不会打印出像John和Joe这样的文件中的其他名称。当用户没有输入名称时我打印Guest,因此它是默认名称。

如何保存以前的名称并添加新名称并对其进行比较和排序,而不是打印它们。

也是我得分的原因。(新得分1(null,0,0,0));在我的构造函数中是因为我想添加默认分数但我认为我做错了所以随意建议任何更改。我试图在文件为空时使用默认值初始化数组。

另一件事我怎样才能在JtextArea上打印arraylist中的元素,以便它们像列表一样打印?

    public class Score1Frame extends javax.swing.JFrame {

    ImageIcon pressPlayAgain = new ImageIcon(getClass().getResource("/images/PlayAgainScorePressed.png"));
    ImageIcon unpressPlayAgain = new ImageIcon(getClass().getResource("/images/PlayAgainScoreUnPressed.png"));
    ImageIcon pressQuit = new ImageIcon(getClass().getResource("/images/QuitScorePressed.png"));
    ImageIcon unpressQuit = new ImageIcon(getClass().getResource("/images/QuitScoreUnpressed.png"));
    GameFrame scores;
    public ArrayList<Score1> score = new ArrayList<Score1>();

    Score1SubmitFrame add;
    // The file 
    private String scoreFile = "score";

    File file = new File(scoreFile);

    /**
     * Creates new form Score1Frame
     */
    public Score1Frame() {
        initComponents();
        //Score1SubmitFrame adds = Score1SubmitFrame();
        setSize(640, 515);
        // Don't allow resizeable
        setResizable(false);
        // Set the title
        setTitle("Rock Paper Scissors
        score.add(new Score1(null, 0, 0, 0));
        score.add(new Score1(null, 0, 0, 0));
        score.add(new Score1(null, 0, 0, 0));
        score.add(new Score1(null, 0, 0, 0));
        score.add(new Score1(null, 0, 0, 0));
        fileEmpty();
        addScore();
        addScoresToFile();
        sortScore();

        displayScore();


    }

    public void fileEmpty() {

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            if (br.readLine() == null) {
                // If the file is empty call the default scores method
//                for (int i = 0; i >= 5; i++) {
//                    defaultScore();
//                }

                score.add(new Score1(null, 0, 0, 0));
                score.add(new Score1(null, 0, 0, 0));
                score.add(new Score1(null, 0, 0, 0));
                score.add(new Score1(null, 0, 0, 0));
                score.add(new Score1(null, 0, 0, 0));
                System.out.println("File has default values since it was empty");
            }
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "Please close the program, as we will try to resolve the issue.", "File Not Found", JOptionPane.ERROR_MESSAGE);
            //createFile();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "It seems as there was an issue displaying the leaderboards. Please close the game and reopen the game. Thank You", "Can't Open Leaderboards", JOptionPane.ERROR_MESSAGE);

        }

    }

//    public void createFile() {
//
//        try {
//            // Create the file
//            FileOutputStream fileScore = new FileOutputStream(file);
//            // Close the file
//            fileScore.close();
//        } catch (FileNotFoundException ex) {
//
//        } catch (IOException ex) {
//
//        }
//
//    }
    // The method that adds the score to the arraylist
    public void addScore() {
        // Score1SubmitFrame object to allow me acess to the class
        add = new Score1SubmitFrame();
        // GameFrame object to allow me access to the class
        scores = new GameFrame();
        // Add the score to the arraylist
        score.add(new Score1(add.userName(), scores.getFinalWin(), scores.getFinalDraw(), scores.getFinalLose()));
        // Declare an iterator
        Iterator<Score1> list = score.iterator();
        // Go through the arraylist
        while (list.hasNext()) {
            Score1 scoreAdd = list.next();
            System.out.println("Score was added");
        }
    }
    // The method that adds the score to the file
    public void addScoresToFile() {

        try {
            // Create the file
            FileOutputStream myFile = new FileOutputStream(file);
            // Create the object that will write to the file
            ObjectOutputStream os = new ObjectOutputStream(myFile);
            // Iterate through the array
            for (Score1 h : score) {
                // Write the scores to the file
                os.writeObject(h);
            }
            myFile.close();
            os.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Score1Frame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Score1Frame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void displayScore() {
        int id = 1;

        try {

            FileInputStream inFile = new FileInputStream(file);
            ObjectInputStream openFile = new ObjectInputStream(inFile);

            //score = (ArrayList<Score1>) openFile.readObject();
            //Score1 b = (Score1) openFile.readObject();
//            for (Score1 add : score) {
//                  //highScore.setText(id + ": " + add.name + " Wins: " + add.wins + ", Draws: " + add.draws + ", Loses: " + add.loses);
//                //highScore.setText(score);
//                System.out.println(score);
//                id++;
//            }
            try {
                while (true) {
                    Score1 bc = (Score1) openFile.readObject();
                    score.add(bc);
                    System.out.println(bc.name + " Wins : " + bc.wins);
                }
            } catch (EOFException e) {

            }
            System.out.println("---- Display ----");
//            for (Score1 s : score) {
//                System.out.println(id + ": " + s.name + " Wins: " + s.wins + " Draws: " + s.draws + " Loses: " + s.loses);
//                highScore.setText(id + ":" + s.name + " Wins: " + s.wins + " Draws: " + s.draws + " Loses: " + s.loses);
//                id++;
//                if (id >= 5) {
//                    break;
//                }
//            }
            // Test here
            System.out.println("---------------------- Other -------------------");
            Iterator<Score1> list;

            for(int i = 0; i < 1; i++){
                list = score.iterator();

                while(list.hasNext()){
                    Score1 s = list.next();
                    highScore.setText(id + ":" + s.name + " Wins: " + s.wins + " Draws: " + s.draws + " Loses: " + s.loses);
                    System.out.println(id + ":" + s.name + " Wins: " + s.wins + " Draws: " + s.draws + " Loses: " + s.loses);
                    id++;
                    if (id == 5){
                        break;
                    }
                }


            }
            openFile.close();
            inFile.close();

        } catch (FileNotFoundException e) {
            Logger.getLogger(scoreFile, scoreFile);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Score1Frame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassCastException e) {

        }

        addScoresToFile();
//        for (Score1 d : score) {
//            //System.out.println(d.name +"Wins: "+ d.wins);
//            highScore.setText(id + ": " + d.name + " Wins: " + d.wins + ", Draws: " + d.draws + ", Loses: " + d.loses);
//            id++;
//        }

    }


    public void writeScores() {

        try {
            FileOutputStream fs;
            fs = new FileOutputStream(file);
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(score);
            os.close();
        } catch (FileNotFoundException ex) {
            //createFile();
            JOptionPane.showMessageDialog(null, "Please close the program and try again as we try to resolve the issue ", "File Not Found", JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "It seems as there was an issue displaying the leaderboards. Please close the game and reopen. Thank You", "Can't Open Leaderboards", JOptionPane.ERROR_MESSAGE);
        } finally {

        }
    }

    public void defaultScore() {
        score.add(new Score1(null, 0, 0, 0));
    }

    public void sortScore() {
        Iterator<Score1> list = score.iterator();
        int rank = 1;
        for (int i = 0; i < 1; i++) {
            Collections.sort(score, new ScoreComparator());
            list = score.iterator();
            while (list.hasNext()) {
                Score1 b = list.next();
                //System.out.println(rank +": "+ b.name + "Wins: "+ b.wins + ", Draws: "+ b.draws + ", Loses: "+b.loses);
                //highScore.setText(rank + ": " + b.name + " Wins: " + b.wins + ", Draws: " + b.draws + ", Loses: " + b.loses + "\n");
                //rank++;
            }
        }
    }

    private class ScoreComparator implements Comparator<Score1> {

        @Override
        public int compare(Score1 s1, Score1 s2) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            if (s1.wins == s2.wins) {
                return 0;
            } else if (s1.wins > s2.wins) {
                return -1;
            } else {
                return 1;
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

  

保存以前的名称并添加新名称

您必须以附加模式打开文件。

您可以使用FileOutputStream构造函数的另一种实现,即

public FileOutputStream(File file, boolean append)

参考:https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html#FileOutputStream-java.io.File-boolean-

  

比较并排序然后打印出来。

我建议您查看SortedSetTreeSet。与Score Comparator一起使用它可以在您将项目添加到Set时自动对元素进行排序。