Good Evening

I have been stuck for a while now while trying to figure out how i can keep my ArrayList sorted when it receives new input.

I tried the collections.sort(scores) but i get a error saying
"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>>"

What i now understand is that i need to have a Comparator?

I have been studying that one for the past 2 hour but i really cant figure it out.
Maybe i am to far ahead from where the teacher wants us to be, but this is the game i built and that i find works decently well.

So if some kind soul out there could try to explain it better then the examples out there i would be super happy. Or break it up so even this 1 month old programmer could work with it.

Best Regards
//Martin

import java.util.*;

public class Start {
    
    public static void main(String[] args) {

        ArrayList<Score> scores = new ArrayList<Score>();
        
        Scanner input = new Scanner(System.in);
        {
            Game2 newGame = new Game2();
            newGame.Start();
        }
    }
}
import java.util.*;
import java.io.*;

public class Game2 {


    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("\n\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("\nGuess a number between 0 and 1000");
            long startTime = System.currentTimeMillis();
            
            while (guess != number){

            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("Try a number between 0 and 1000 instead.");
            }

            

            if (guess > number && guess < 1001) {
                System.out.println("Your guess is too high");
            tries++;
            }
            else if (guess < number && guess >= 0) {
                System.out.println("Your guess is too low");
            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("\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!");   
                 

                }
                
            }
            }
        }
    }
   }
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;
    }
}

error saying
"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>>"

Which line in your code is causing this error?

Oh, terribly sorry. It was so late (or early) so i forgot to enter that code part again.

Game2 on line 82. Right before the "for" loop. i entered

collections.sort(scores)

Should it maybe be put elsewhere?

//Martin

In order to be able to sort instances of some class (such as Scores) you need to be able the compare two Scores to see what order to sort them in. Scores is a class you define, so there's no sensible guess that Java can make about what order you want. To fix this you must implement the Comparable interface in your class. This consists of only 1 method to compare two Scores and say which sorts first. Have a look at this:
http://onjava.com/pub/a/onjava/2003/03/12/java_comp.html

commented: Greatly helpful post +1

Thanks for that James.

I think i studied a similar page before.

I just cant figure out, as i want to compare the number of tries to itself.
Can i compare object X to object X? I mean can and how do i compare it to itself.

Or is the first score input object X and then the next becomes object Y?

You are comparing one instance of class Score to another instance of class Score.
The method will be called by the sort routing sonething like this:
score1.compareTo(score2);
so in your compareTo method you are comparing "this" with the Score passed as a parameter. If those two instances are the same instance, just return 0 (ie "equal").

Hello again

So i tried to fix my comparator interface, and i think i somewhat got it now.
The last class has that at the end.

But even when i try to do the Collection.sort in my guessNumber class i get that long messy error.

Line 80.

Have i still missed something vital to this? I am fumbling in the dark at the moment and i hope to see the light soon enough..

import java.util.*;

public class Game {
	
	public static void main(String[] args) {

		List<Score> scores = new ArrayList<Score>();
	    Scanner input = new Scanner(System.in);
	    {
	    	guessNumber newGame = new guessNumber();
	    	newGame.Start();
	    }
	}
}
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!");   
                 

                }
            }
        	}
        }
    }
   }
import java.util.*;


public class Score implements 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;
			}

			
}

What is the exact error message?

"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>>"

The same as before when i didnt have my compareTo

Does line 26 really say "pulbic" ????

Does line 26 really say "pulbic" ????

It really did. I fixed that tho but it didn't change anything sadly.

It somehow feels like it doesnt see my Score class.
But also when i change around in the "toString" it does change.

But the collection.sort cant find the comparable interface?

I copied the essential bits of your code and compiled and ran the following

class Score implements Comparable<Score> {

   int theScore;
   String playerName;

   public Score(int theScore, String playerName) {
      this.theScore = theScore;
      this.playerName = playerName;
   }

   public int getScore() {
      return theScore;
   }

   public int compareTo(Score sc1) {
      if (getScore() < sc1.getScore()) return -1;
      if (getScore() > sc1.getScore()) return 1;
      return 0;
   }

   public String toString() {
      return playerName + "\t" + " " + theScore;
   }
}
public static void main(String args[]) throws Exception {

      ArrayList<Score> scores = new ArrayList<Score>();
      scores.add(new Score(99, "fred"));
      scores.add(new Score(0, "joe"));
      scores.add(new Score(50, "bill"));
      Collections.sort(scores);
      for (int i = 0; i < scores.size(); i++) {
         System.out.println(scores.get(i));
      }

This compiles and runs perfectly (Java 1.6u21), so what else is there in your full code that is preventing this fromworking?

I really have no idea at the moment.

It works on my laptop but not on my stationary computer.

It actually sorts after score now, so now i need to fix it to sort by time if the scores are the same.

can you put an If()return == 0) do ->?
I probably need to find a away to turn my getTime variable from a double to an int too..

so much work when you think you are close, and only until Friday to complete it.

But again, thanks a lot. It helped me immensely!

Yes, you can use all the normal if test etc so if the scores are the same you go on the compare the times.
Either you have inconsistent versions (maybe old class files etc) or an old version of Java on your desktop?

Thanks a lot James. Your help really got me through that part.

Now i found some other bugs tho thats starting to become a pain in the #"%.

Like, i need to start the

long startTime = System.currentTimeMillis();

After the first entry and then keep it rolling untill he gets it correct. But as it looks now it resets after each entry.. and if i put it with the first loop it starts to count right as you starts the game.

Also if you have entered an integer thats say, too low. And then type in a string it will to both the NumberFormatException and the too low part. So it prints out both of those faults.

Both those sound like straightforward logic things. I'm sure you will be able to think through them.
Maybe it's time to mark this thread as solved? Any new problems deserve a new thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.