Results 1 to 16 of 16
  1. #1
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default Java - Comparator, sorting arrayLists

    Hi

    So as you might guessed i am trying to sort my arrayList of scores.

    I have been instructed to look at the comparator and compareTo().
    And i have really been trying, i tried to look at examples, guides and the API.

    But it just wont stick, i just cant figure out where to put the compareTo and how to implement it.

    Is there any kind soul out there who could try to point/show/tell how i can get this to work?

    Best regards
    //Martin

    Java Code:
    import java.util.*;
    
    public class Game {
    	
    	public static void main(String[] args) {
    
    		/*ArrayList<Score> scores = new ArrayList<Score>();
    		
    	    Scanner input = new Scanner(System.in);*/
    	    {
    	    	guessNumber newGame = new guessNumber();
    	    	newGame.Start();
    	    }
    	}
    }
    Java Code:
    import java.util.*;
    
    
    public class Score {
    	
    	int theScore = 0;
    	double theTime = 0;
    	String playerName;
    	
    
    	public Score (int theScore, double theTime, String playerName){
    		this.theScore = theScore;
    		this.theTime = theTime;
    		this.playerName = playerName;
    		}
    	
    	public String toString(){
    		
    		String highScorelist = (playerName + "\t" + " " +  theScore + "\t" +" " + ((int)theTime/1000));
    		return highScorelist;
    	}
    }
    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class guessNumber {
    
    
        public void Start() {
    
        	
            Random random = new Random();
            boolean playAgain = true;
    
            String answer = "Yes";
            String quit = "Quit";
    
            ArrayList<Score> scores = new ArrayList<Score>();
    
            while (playAgain == true)
            {
            	System.out.println("\nWelcome to Guess the Number!!");
            	String name;
                int guess = -1;
                int tries = 0;
                int number = random.nextInt(1000) + 1;
                System.out.println(number);
            	Scanner input = new Scanner(System.in);
                System.out.println("\nPlease guess a number between 0 and 1000: ");
                
            	while (guess != number){
                long startTime = System.currentTimeMillis();
                String guess1 = input.next();
                
                
                if (guess1.equalsIgnoreCase(quit))
                { 
                	System.out.println("Thanks for playing!");
                	System.exit(0);
                }
                
                try {
                	guess = Integer.parseInt(guess1);
                } catch (NumberFormatException nfe) {
                	System.out.println("Please enter a \"Number\" between 0 and 1000: ");
                }
    
                
    
                if (guess > number && guess < 1001) {
                    System.out.println("Your guess is too high, try with a lower number: ");
                tries++;
                }
                else if (guess < number && guess >= 0) {
                    System.out.println("Your guess is too low, try with a higher number: ");
                tries++;
                }
                if (guess <-1 || guess > 1001) {
                    System.out.println("Try between 0 and 1000 instead: ");
                }
                
                if (guess == number) {
                    System.out.println("\nCorrect!");
                tries++;
                long endTime = System.currentTimeMillis();
    			long gameTime = endTime - startTime;
        
                
                
                System.out.println("\nYou guess the correct answer in " + tries + " tries and " + (gameTime/1000) + " seconds" );
                    
                System.out.println("\nEnter your name: ");
                name = input.next();
                
    			Score currentScore = new Score(tries, gameTime, name);
    			scores.add(currentScore);
    			        	
                    System.out.print("\nPlay again? (Yes or No)" );
                    name = input.next();
    
                    if (answer.equalsIgnoreCase("Yes")) {
                    	System.out.println("\nHigh Score\nName \t Guess \t Time");
                    	for (int i = 0;i < scores.size(); i++)
        				{
        				System.out.println(scores.get(i));
        				
                    	playAgain = true;
        				}
                    }
                    else if (answer.equalsIgnoreCase("N")) {
                         playAgain = false;
                    }
                    else {
                        playAgain = false;
                     } 
                    if (playAgain == false) {
                     System.out.println("\nThank you for playing!");   
                     
    
                    }
                }
            	}
            }
        }
            
    
        
        
        
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    We shouldn't do this for you, and for us to be able to help you, we need to better understand what mistakes you're making, and so you probably should show us your attempt to use Comparable or Comparator.

  3. #3
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default

    Well since i dont know where to put it its hard to try.

    Maybe you know of some tutorial i missed, some other work out there that has what i am seeking so i can study that and learn that way.

    Because checking the API i really cant figure it out, i might be dumb or what nots, but the API just isnt doing it for me this time.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    There are several decent tutorials that you can find if you search Google for Java Comparable Tutorial

    To get you started, I recommend that you have Score implement the Comparable<Score> interface and give it a compareTo method that takes another Score object. The key will be what you put in this compareTo method.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Kerrai View Post
    Because checking the API i really cant figure it out, i might be dumb or what nots, but the API just isnt doing it for me this time.
    Also, if you have any specific questions about aspects of the API or tutorials, please ask. Those are questions we can usually answer well.

  6. #6
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default

    Hello again

    So i have tried to fix this now, and what i came up with was

    Java Code:
    import java.util.*;
    
    
    public class Score implements interface Comparable<Score>{  
    	int theScore;
    	double theTime;
    	String playerName;
    
    	public Score (int theScore, double theTime, String playerName){
    		this.theScore = theScore;
    		this.theTime = theTime;
    		this.playerName = playerName;
    		}
    	public int getScore() {
            return theScore;
        }
    
        public String getName() {
            return playerName;
        }
        public int getTime() {
        	return theTime;
        }
    	
    	pulbic int compareTo(Score sc1) {
                    if(getScore() < sc1.getScore()) return -1;
    		if(getScore() > sc1.getScore()) return 1;
    		return 0;
    	}
    
    
    	public String toString(){
    		
    		String highScorelist = (playerName + "\t" + " " +  theScore + "\t" +" " + ((int)theTime/1000));
    		return highScorelist;
    	}
    
    			
    }
    But this seems to do nothing at all.
    It also feels like i am missing something, somewhere.. i just cant think of what. It feels like i am blinded by my code..
    Am i on the right track or am i lost in limbo and just stabbing a dead bull here?
    Last edited by Kerrai; 10-24-2010 at 05:04 PM.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    It's looking a LOT better, and in fact I think your use of Comparable is spot on -- well done! Now all you have to do is fill up the ArrayList<Score> with data, and then sort it. The list can be sorted via the Collections.sort(List list) method.

  8. #8
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    It's looking a LOT better, and in fact I think your use of Comparable is spot on -- well done! Now all you have to do is fill up the ArrayList<Score> with data, and then sort it. The list can be sorted via the Collections.sort(List list) method.
    I played around with the Collection.sort a little.

    But where ever i put it it didnt seem to do anything.

    Any hint on where this should be put?
    Or does it require its own method in one of my classes?

    btw, thanks a lot for the helpful "get me started" tip, it really helped.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The only recommendation I can think of giving you is that you call the sort method after the arraylist is full of the data that needs to be sorted. That's it. If it still doesn't work, please post your code where you try to use it.

  10. #10
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default

    Well. i want to put it here

    Java Code:
    if (answer.equalsIgnoreCase("Yes")) {
                    	System.out.println("\nHigh Score\nName \t Guess \t Time");
                    	Collections.sort(scores);
                    	for (int i = 0;i < scores.size(); i++)
                    	{
                    	System.out.println(scores.get(i));
                    	playAgain = true;
        				}
                    }
    (i hope thats enough code?)

    But if i put that in the guessNumber class i get an error called
    Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments
    (ArrayList<Score>). The inferred type Score is not a valid substitute for the bounded parameter <T extends
    Comparable<? super T>>

    So its either wrong, or something else is wrong.
    But if i put it somewhere in the Score class nothing happens.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  12. #12
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default

    Alright

    Game Class, that "starts" the program
    Java Code:
    import java.util.*;
    
    public class Game {
    	
    	public static void main(String[] args) {
    
    		ArrayList<Score> scores = new ArrayList<Score>();
    	    Scanner input = new Scanner(System.in);
    	    {
    	    	guessNumber newGame = new guessNumber();
    	    	newGame.Start();
    	    }
    	}
    }
    guessNumber class where the magic happens.
    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class guessNumber {
    
    
        public void Start() {
    
        	
            Random random = new Random();
            boolean playAgain = true;
    
            String answer = "Yes";
            String quit = "Quit";
    
            ArrayList<Score> scores = new ArrayList<Score>();
            while (playAgain == true)
            {
            	System.out.println("\nWelcome to Guess the Number!!");
            	String name;
                int guess = -1;
                int tries = 0;
                int number = random.nextInt(1000) + 1;
                System.out.println(number);
            	Scanner input = new Scanner(System.in);
                System.out.println("\nPlease guess a number between 0 and 1000: ");
                
            	while (guess != number){
                long startTime = System.currentTimeMillis();
                String guess1 = input.next();
                
                
                if (guess1.equalsIgnoreCase(quit))
                { 
                	System.out.println("Thanks for playing!");
                	System.exit(0);
                }
                
                try {
                	guess = Integer.parseInt(guess1);
                } catch (NumberFormatException nfe) {
                	System.out.println("Please enter a \"Number\" between 0 and 1000: ");
                }
    
                
    
                if (guess > number && guess < 1001) {
                    System.out.println("Your guess is too high, try with a lower number: ");
                tries++;
                }
                else if (guess < number && guess >= 0) {
                    System.out.println("Your guess is too low, try with a higher number: ");
                tries++;
                }
                if (guess <-1 || guess > 1001) {
                    System.out.println("Try between 0 and 1000 instead: ");
                }
                
                if (guess == number) {
                    System.out.println("\nCorrect!");
                tries++;
                long endTime = System.currentTimeMillis();
    			long gameTime = endTime - startTime;
        
                
                
                System.out.println("\nYou guess the correct answer in " + tries + " tries and " + (gameTime/1000) + " seconds" );
                    
                System.out.println("\nEnter your name: ");
                name = input.next();
                
    			Score currentScore = new Score(tries, gameTime, name);
    			scores.add(currentScore);
    			
                    System.out.print("\nPlay again? (Yes or No)" );
                    name = input.next();
    
                    if (answer.equalsIgnoreCase("Yes")) {
                    	System.out.println("\nHigh Score\nName \t Guess \t Time");
                    	Collections.sort(scores);
                    	for (int i = 0;i < scores.size(); i++)
                    	{
                    	System.out.println(scores.get(i));
                    	playAgain = true;
        				}
                    }
                    else if (answer.equalsIgnoreCase("N")) {
                         playAgain = false;
                    }
                    else {
                        playAgain = false;
                     } 
                    if (playAgain == false) {
                     System.out.println("\nThank you for playing!");   
                     
    
                    }
                }
            	}
            }
        }
       }
    Score class that handles the list
    Java Code:
    import java.util.*;
    
    
    public class Score implements interface Comparable<Score>{  
    	int theScore;
    	double theTime;
    	String playerName;
    
    	public Score (int theScore, double theTime, String playerName){
    		this.theScore = theScore;
    		this.theTime = theTime;
    		this.playerName = playerName;
    		}
    	public int getScore() {
            return theScore;
        }
    
        public String getName() {
            return playerName;
        }
        public int getTime() {
        	return theTime;
        }
    	
    	pulbic int compareTo(Score sc1) {
    		if(getScore() < sc1.getScore()) return -1;
    		if(getScore() > sc1.getScore()) return 1;
    		return 0;
    	}
    
    
    	public String toString(){
    		
    		String highScorelist = (playerName + "\t" + " " +  theScore + "\t" +" " + ((int)theTime/1000));
    		return highScorelist;
    		Collections.sort(List scores);
    	}
    
    			
    }
    Thanks for taking your time

  13. #13
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Java Code:
    public class Score implements interface Comparable<Score>{
    not sure keyword interface should be there
    Last edited by al_Marshy_1981; 10-24-2010 at 07:17 PM. Reason: ...

  14. #14
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Yep, it's
    Java Code:
    public class Score implements Comparable<Score>{
      //....

  15. #15
    Kerrai is offline Member
    Join Date
    Oct 2010
    Posts
    12
    Rep Power
    0

    Default

    pulbic int compareTo(Score sc1) {

    Is changed to public.

    Strange that eclipse didn't filed that as an error tho

    It didn't fix my Collection.sort either.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    Java Code:
    public class Score implements interface Comparable<Score>{
    not sure keyword interface should be there


    Quote Originally Posted by curmudgeon View Post
    Yep, it's
    Java Code:
    public class Score implements Comparable<Score>{
      //....

    :Sheepish_Grin:
    Oops... Missed that -- sorry!!!

Similar Threads

  1. java.util.Comparator Implementation
    By Navatha in forum New To Java
    Replies: 6
    Last Post: 11-05-2010, 02:48 AM
  2. how to use comparator
    By KidneyinaCooler in forum Advanced Java
    Replies: 2
    Last Post: 07-18-2010, 11:25 AM
  3. implements java.util.Comparator<type>
    By finn in forum New To Java
    Replies: 2
    Last Post: 05-14-2010, 07:58 PM
  4. Use different comparator for SortedSet
    By linus_k in forum New To Java
    Replies: 0
    Last Post: 11-21-2008, 03:46 PM
  5. How to write your own Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 08:38 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •