Mohammed Mohammed - 6 months ago 25
Java Question

If Statement error on array


In the first image, you have an array of players, namely

Player[] p = new Player[2];

When you attempt to compare them is when you run into problems. The > operator can't act on objects that do not have specified comparison methods (i.e. int, double). If you wanted to, for example, compare the scores of the Players, it would be better to use an if statement like:

if( p[0].getScore() > p[1].getScore() )

This way, you are comparing ints, which you can compare, instead of Players which you can't.

Otherwise you could override the compareTo method of the Player class as below:

public int compareTo( Player otherPlayer )
   return this.getScore() - otherPlayer.getScore();

and then with your if statement

if( p[0].compareTo(p[1]) > 0 )

This should sort out the error you are having and make the code at least run.