Help me with Java code?

StachuK1992

statue
Joined
Jul 24, 2008
Messages
3,812
Location
West Chester, PA
WCA ID
2008KORI02
YouTube
Visit Channel
Hello fellow programmer(s),

I have been creating a high-score table for my school's 'gaming club' (unofficial), and am having some difficulties with one of my methods. I'd like to have it so, as scores are entered, they are automatically placed in the correct spot (by score, place(x) being the highest/lowest score) of the collection, as well as with their Name and Date achieved.

My code can be seen at the following website:
http://codeviewer.org/view/code:6f4

The function that needs corrected is called 'addScore.'
I'm not amazing at programming, so please don't go too in-depth with this :p.

Thanks in advance,
Stachu Korick
 
i dont know java but what i found after posting one of my programs here is that you can create an account on http://compsci.ca/v3/ and post a topic, and you will get the best help from experts within hours.

EDIT: dont forget to also check out the already posted topics on http://compsci.ca/v3/ before posting. i am sure someone has had a related problem before. ;)
 
You have something you want to sort? If you create a class that contains the score details and implements the interface java.lang.comparable then the Collections framework will sort a collection of these objects for you.

At present you have three ArrayList objects inthe MameGame class that are logically associated: these should really be part of the same collection. The technique of trying to insert a score into a list... well, for one thing this will grind to a halt over time as these ArrayList instances will have to reallocate themselves in memory - this indicates that a LinkedList is more appropriate. Also consider the further usage of the high score tables, e.g. when you want to see who scores well in various games, this would indicate the use of collections with other lookup means: say, a LinkedHashMap or similar.
 
You have something you want to sort? If you create a class that contains the score details and implements the interface java.lang.comparable then the Collections framework will sort a collection of these objects for you.

At present you have three ArrayList objects inthe MameGame class that are logically associated: these should really be part of the same collection. The technique of trying to insert a score into a list... well, for one thing this will grind to a halt over time as these ArrayList instances will have to reallocate themselves in memory - this indicates that a LinkedList is more appropriate. Also consider the further usage of the high score tables, e.g. when you want to see who scores well in various games, this would indicate the use of collections with other lookup means: say, a LinkedHashMap or similar.

I'm sorry, but I'm kind of (well, really) a Java n00b...
How would one go about turning my 3 ArrayList objects into one?

I don't at all know how to deal with 'LinkedHashMap' or 'LinkedList'(3 arraylists?).

Thanks, I guess :p
Stachu Korick
 
for your constructor MameGame, you do not need to have those.

public void printScores() {
for(int x = 0; x < scoreList.size(); x++)
System.out.print("A score of "+scoreList.get(x)+" was achieved by "+nameList.get(x)+ " on "+ dateList.get(x));
}

I'm pretty sure you can just insert them and do array.sort becuase they're all comparable
If not, then you use a better sorting algorithm. Yours runs with order of n^2.

A linkedlist is kind of like looking at a line.
You can pop (take the first item)
Peek (look at the first item)
Delete (remove last one) hmmm i forgot
It deletes with order of 1 so it's very efficient. It also uses less memory.
 
Last edited:
Basically, you should make a "Score" class, so that you can create a LinkedList of "Score" objects, and easily sort the "Score" objects by score.

A Score class would look something like:
Code:
public class Score{
    int score;
    String name, date;
    Score([color="gray"]n,s,d[/color]){
        [i][color="green"]// constructor[/color]
        [color="gray"]... just assign the values...[/color][/i]
    }
}

Then to sort them, you would need a custom comparator, so that you can easily just call Collections.sort() on it. Finding a simple tutorial on it might be a challenge (I'd know... I've never personally tried this before, I just read up on some tutorials how to do this [so I haven't tested it]), so you can use this instead if you are struggling to find a decent tutorial:

Code:
import java.util.Comparator;

public class ScoreComparator implements Comparator<Score>{

    @Override
    public int compare(Score s1, Score s2){
        if (s1.score > s2.score)
            return +1;
        else if (s1.score < s2.score)
            return -1;
        return 0;
    }
}

Then, you would add a "sortScores()" function to your MameGame class, which you would call only when you need to print the data, so that you just keep adding Scores to the record without having to sort through all the elements each time you add a new one.

Also, you might want to have a flag as to whether your data is sorted, so that it won't have to be re-sorted again everytime it is printed.

Basically, you'd modify your class to something like:
Code:
class MameGame{
    List<Score> scores;
    ScoreComparator comparator;
    boolean isSorted;

    public MameGame(){
        comparator = new ScoreComparator(); [color="green"]//custom comparator to compare "Score" objects[/color]
        scores = new LinkedList<Score>(); [color="green"]//linked list of scores[/color]
        isSorted = false;
    }

    public void printScores(){....}

    public void addScore([color="gray"]n,s,d[/color]) {
	score = new Score([color="gray"]n,s,d[/color]);
        [color="gray"].....code to add score to linked list.......[/color]
        isSorted = false;
    }

    public void sortScores(){
        if (!isSorted) {
            [b]Collections.sort(scores,comparator);[/b] [color="green"]//automatically sort the scores[/color]
            isSorted = true;
        }
    }
}

So that your main function would be like:
Code:
public static void main(String args[]) {


    MG dk = new MG();

    dk.addScore(....);
    dk.addScore(....);
    [color="gray"]....[/color]
    dk.addScore(....);
    dk.addScore(....);
    [color="green"]// just add everything first[/color]

    dk.sortScores();
    dk.printScores();
}

Basically, people can just keep adding scores, and you sort only when you have to display the scores. You could also call sortScores() automatically from within printScores(), but I did it this way so you can more easily see how it works.
 
Last edited:
I'm sorry for double-posting, but there is an update in place, and besides, this won't affect my post-count anyway, will it?(Off-Topic stuff usually won't)

Anywho, I thank bundat a lot, but still have 2 errors that I can't fix
Code, up to date, can be found here:
http://codeviewer.org/view/code:6ff
ugh...harder than I expected

BTW, I have no idea how ScoreComparator works.
At all.

Thanks again,
StachuK1992
 
Code:
import java.util.Comparator;

public class ScoreComparator implements Comparator<Score>{

    @Override
    public int compare(Score s1, Score s2){
        if (s1.score > s2.score)
            return +1;
        else if (s1.score < s2.score)
            return -1;
        return 0;
    }
}

Is there a reason why you're using a ScoreComparator instead of just making the Score class itself Comparable (like msemtd suggested)?
 
I'm sorry for double-posting, but there is an update in place, and besides, this won't affect my post-count anyway, will it?(Off-Topic stuff usually won't)

Anywho, I thank bundat a lot, but still have 2 errors that I can't fix
Code, up to date, can be found here:
http://codeviewer.org/view/code:6ff
ugh...harder than I expected

BTW, I have no idea how ScoreComparator works.
At all.

Thanks again,
StachuK1992

Code:
ScoreList.add() = new OneScore(name, scoreTemp, d);
=>
Code:
ScoreList.add(new OneScore(name, scoreTemp, d));

That's really basic Java knowledge. I suggest going back to a basic tutorial and writing more simple programs until you fully understand methods and Objects and ...
btw. Object names are written in lower camel case in Java.

No.
Bundat just seemed to give the best(well, lengthiest) resonse, so I went with him.
How would I go about making the Score class comparable?

Actually i asked Bundat.
 
@tim: Well, I originally did that to keep things simple and understandable to him (I think he would find using a simple Score class, or OneScore in his code's case, without any implements or methods overrides, less intimidating than creating a list of objects using a class that implements Comparable and overrides compareTo). i.e. it was an attempt to segregate code or concepts which would probably be beyond his level (implementing interfaces on objects) into a "black box" of sorts.

My post was designed to keep it simple so that it would be easy for the topic starter to understand...
so you (@Stachuk: ) shouldn't just copy it (your second error just makes me scratch my head, check your variable names)
and also try to do a bit of research on it too (if you googled "java linkedlist tutorial" for your first error, you'll easily find an answer... I tried to keep it simple by using a temporary variable so that you wouldn't have to deal with messy code containing nested expressions, and you could simply do a "ScoreList.add(score)" to replace my ".....code to add score to linked list......." line).

Although seeing code that attempts to assign a value to a method call tells me you need to work more on your basics first.

BTW, I have no idea how ScoreComparator works.
At all.

When you call Collections.sort(list,criteria), it sorts the elements in the list, using the criteria specified.
So when I do Collections.sort(usernamesList,alphabetical), it will sort the list of usernames alphabetically.

ScoreComparator is just a criteria I created, to sort a list of scores according to the score value in the OneScore object, ignoring the name and date values. Actually, I think it sorts it in ascending order, quite the opposite of what you needed.

How would I go about making the Score class comparable?
Get rid of the ScoreComparator class altogether, move the overridden compare method into the OneScore class, renaming it to compareTo, and also fix it to accept only one parameter and instead compare "this" and the object from the parameter, and implement Comparable with OneScore like how ScoreComparator implements Comparator.

If the steps sound too complicated or are hard to understand from that sentence, google comparable interface compareto override and you're bound to find example tutorials.

@tim: I just thought that doing it like that would be too complicated for him.
 
Last edited:
Know what?
I feel as though a lot of this went over my head, but I did indeed learn a good bit, and I thank you for that.
I'm going to try and put things in terms I can understand now; I think I've found out a way to do this(fairly inefficiently :( , however)
Thanks again,
StachuK1992
 
Know what?
I feel as though a lot of this went over my head, but I did indeed learn a good bit, and I thank you for that.
I'm going to try and put things in terms I can understand now; I think I've found out a way to do this(fairly inefficiently :( , however)
Thanks again,
StachuK1992

I recommend you read the Java Tutorial and Bruce Eckel's Thinking in Java.
 
Back
Top