2
\$\begingroup\$
import java.util.*;
import java.io.*;

public class Player
{
    Scanner read;
    PrintWriter write;

    private String playerid;
    private int playerscore;

            int x = 0;
            ArrayList<String> n = new ArrayList<String>();
            ArrayList<Integer> s = new ArrayList<Integer>();
            List<Player> players = new ArrayList <Player>();

    public Player (String name, int score)
    {
        playerid = name;
        playerscore = score;


    }


        static class ScoreComparator implements Comparator <Player>
    {
        public int compare(Player lf1, Player lf2)
        {
            int scoreA = lf1.getScore ();
            int scoreB = lf2.getScore ();

            if (scoreA == scoreB)
            {
                return 0;
            }

            else if (scoreA > scoreB)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
    }

        public String getName()
        {
            return playerid;
        }

        public int getScore()
        {
            return playerscore;
        }

        public String toString ()
        {
            return playerid+"\t "+playerscore;
        }


        public void loadScores()
        {


            try
            {
                read = new Scanner (new FileReader ("lbout.txt"));

            while (read.hasNext ())
            {

            n.add (read.next ());

            s.add(read.nextInt ());
            }
                System.out.println(n);
                System.out.println(s);
            }
            catch (FileNotFoundException fnfe)
            {
                System.out.println(fnfe+": FILE NOT FOUND!");
            }
            catch (InputMismatchException ime)
            {
                System.out.println(ime+": INVALID DATA!");
            }
            catch (Exception e)
            {
                System.out.println(e);
            }


        }


        public void evaluateScores()
        {
            try
            {
                loadScores ();

                n.add (playerid);
                s.add(playerscore);

            //  sortScores();
            int u;
            int max = 5;



            for (u = 0; u < n.size (); ++u)
            {
                players.add(new Player (n.get (u),s.get (u)));


            }
            Collections.sort (players, Collections.reverseOrder (new Player.ScoreComparator()));

            for (int j = 0; j < max; ++j)
            {
                System.out.println("\t "+players.get(j));
            }

            ArrayList <Player> arr = new ArrayList<Player>();

            for (int y = 0; y < players.size (); ++y)
            {
                arr.add(players.get(y));
                            //I tried to pass the players as an argument to the GUI class but I get an error saying there's a conflict between util and awt so I copied it to an ArrayList
            }


            System.out.println("Print arr:" +arr);

            write = new PrintWriter ("lbout.txt");

            for (int z = 0; z < n.size (); ++z)
            {

                write.print(n.get(z)+" ");
                write.println (s.get(z));

            }
            write.close ();


                //displayScores();


            }

            catch (InputMismatchException ime)
            {
                System.out.println(ime+": INVALID DATA!");
            }
            catch (Exception e)
            {
                System.out.println(e);
            }
        }



}

As you can see, my code (aside from the fact that it isn't highly efficient but I'm not worrying about that at the moment, newbie here) only takes two parameters: one for the winner's name, the other the winner's score. What I'm trying to do is add not only the winner's name and score, but also the loser's, or in other words both of the players' info, but I'm not sure how I will proceed.

So far:

public class PlayerTry {

    private String playeridA;
    private String playeridB;
    private int playerscoreA;
    private int playerscoreB;



    public PlayerTry (String name1, String name2, int score1, int score2)
    {
        playeridA = name1;
        playeridB = name2;
        playerscoreA = score1;
        playerscoreB = score2;

    }

       //Actually PlayerTry is a separate class and it's some sort of my draft space in case I mess up so at least I don't mess up my original code as well.
}

Then they will be added to the n and s list with the other loaded info from the txt file.

I'm not sure about the getName(), getScore(). Should I create separate getName() and getScore() methods for each of the passed players' info?

Hints/suggestions would be appreciated!


EDIT: My program no longer implements the Comparable interface by the way, since I would only be needing for the players' scores to be sorted out, order of names are disregarded.

\$\endgroup\$
5
  • 2
    \$\begingroup\$ This is technically working code (I assume - haven't tried it) but you are still asking "How to add both player's score". This should be in StackOverflow since your program doesn't work the way you want. \$\endgroup\$
    – Max
    Feb 28, 2014 at 10:16
  • \$\begingroup\$ There are some improvements to be done I will end my review soon and paste code. Please keep that question in that forum. \$\endgroup\$
    – RMachnik
    Feb 28, 2014 at 10:25
  • \$\begingroup\$ @Max i asked this first on stackoverflow but i was redirected here. It does work but it's OOP so yeah some parts aren't present \$\endgroup\$ Feb 28, 2014 at 10:29
  • \$\begingroup\$ @lira79915220 Please post the link to the SO question, I can take a look at it. \$\endgroup\$ Feb 28, 2014 at 20:19
  • \$\begingroup\$ @SimonAndréForsberg stackoverflow.com/questions/22090967/… \$\endgroup\$ Mar 3, 2014 at 13:42

1 Answer 1

2
\$\begingroup\$

This is my code review. I added new class ScoringEngine please look on it. There can be made more but you have to specify what you want to achieve. I added some comments in classes.

public class Player //  implements Comparable<Player> there is no need to implement that interface because you use different comparator implemented in GameEngine class
{
    private String playerid;
    private int playerscore;

    int x = 0;
    List<String> n = new ArrayList<String>();
    List<Integer> s = new ArrayList<Integer>();
    List<Player> players = new ArrayList <Player>();

    public Player (String name, int score)
    {
        playerid = name;
        playerscore = score;


    }
    public String getName()
    {
        return playerid;
    }

    public int getScore()
    {
        return playerscore;
    }

    public String toString ()
    {
        return playerid+"\t "+playerscore;
    }



     /* public int compareTo(Player lf)
        {
            return getName ().compareTo (lf.getName ());
        }
       */

}

ScoringEngine

public class ScoringEngine {
  //for general attention is that you can save and read your scores from different files.
    private Scanner read;
    private PrintWriter write;
    final String scoresFileName = "lbout.txt";
    public void evaluateScores()
    {
        try
        {
            List<Player> playerScores = loadScores();

            Collections.sort(playerScores, Collections.reverseOrder(new PlayerComparator()));

            for (Player player : playerScores)
            {
                System.out.println("\t "+player.getName()+ " " + player.getScore());
            }


/*           this can be removed I think

            ArrayList<Player> arr = new ArrayList<Player>();
            for (int y = 0; y < players.size (); ++y)
            {
                arr.add(players.get(y));
                //I tried to pass the players as an argument to the GUI class but I get an error saying there's a conflict between util and awt so I copied it to an ArrayList
            }
*/
             //filenames were the same so I replaced it with one value
            write = new PrintWriter(scoresFileName);

            for (Player player:playerScores)
            {
                write.print(player.getName()+" ");
                final String lineSeparatorKey = "line.separator";     //nice trick to keep code indepentent from platform
                write.println (player.getScore() + System.getProperty(lineSeparatorKey));
            }
            //displayScores();
        }

        catch (InputMismatchException ime)
        {
            System.out.println(ime+": INVALID DATA!");
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
        finally{        // remember to close all file descriptors or streams
            write.close();
        }
    }

    public List<Player> loadScores()
    {
        List<Player> scores = new ArrayList<Player>();
        FileReader source = null;

        try
        {

            source= new FileReader(scoresFileName);
            read = new Scanner(source);

            while (read.hasNext ())
            {
                Player player = new Player(read.next(),read.nextInt()); // this might throw exception because read.hasNext()
                // check weather only one reading can be made not two ->read.next() and read.nextInt()... |
                // To repair it change format of stored data in your file with scores to keep data for one player in one line...
            }
            return scores;
        }
        catch (FileNotFoundException fnfe)
        {
            System.out.println(fnfe+": FILE NOT FOUND!");
        }
        catch (InputMismatchException ime)
        {
            System.out.println(ime+": INVALID DATA!");
        }
        catch (Exception e)
        {
            System.out.println(e);
        } finally{    //remember to close all streams and file descriptors
            assert source != null;
            try {
                read.close();
                source.close();
            } catch (IOException e) {
                System.out.println("PROBLEM WITH CLOSING FILE!");
            }
        }
        return scores;
    }


    private class PlayerComparator implements Comparator<Player>
    {
        public int compare(Player lf1, Player lf2)
        {
            int scoreA = lf1.getScore ();
            int scoreB = lf2.getScore ();

            if (scoreA == scoreB)
            {
                return 0;
            }

            else if (scoreA > scoreB)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
    }

}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Normally I find it easier to follow an answer if the comments aren't within the code. But welcome to Code Review, nice to have you here. \$\endgroup\$ Feb 28, 2014 at 11:13
  • \$\begingroup\$ Sorry :) but it is readable. I was trying to do it simple. \$\endgroup\$
    – RMachnik
    Feb 28, 2014 at 11:19
  • \$\begingroup\$ Thanks for this! However I'm not sure if this is really the right place where I should be asking since I asked first on StackOverflow but I was told to ask it here. I was asking for hints/suggestions since my present code only takes info from a single player, the winner, but what I'm trying to achieve is take info from two players. If I'm doing things the wrong way do me a favor and point it out, newbie here, thanks! \$\endgroup\$ Feb 28, 2014 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.