I recently posted a question about getting a NullPointerException
whenever I called an array of objects. I have traced the problem back to some disconnect between the main method providing the data and the method in question (Team.sortPlayers()
) receiving the data.
public class Project3 {
public static void main(String[] args) {
Input3 input = new Input3();
Team teams[] = new Team[input.NUMBER_OF_TEAMS];
Player players[] = new Player[input.NUMBER_OF_PLAYERS];
String playas[] = new String[input.NUMBER_OF_PLAYERS];
String temp;
String name;
for ( int i=0 ; i<input.NUMBER_OF_TEAMS ; i++ ) {
name = input.getNextString();
System.out.println(name);
for ( int j=0 ; j<input.NUMBER_OF_PLAYERS ; j++ )
{playas[j] = input.getNextString();
System.out.println(playas[j]);}
teams[i] = new Team(name, playas); //THIS LINE SENDS OVER THE DATA TO THE QUESTIONABLE METHOD
teams[i].sortPlayers();
System.out.println(teams[i]);
}
}
}
//------------------------------
//
//------------------------------
class Player {
public String[] name;
public Player(String inputname) {
name = inputname.split(" ");
}
public String[] getName() {
return name;
}
public String getFirstName() {
return name[0];
}
public String getLastName() {
String last = name[1];
return last;
}
}
//-----------------------
//
//-----------------------
class Team {
private String teamname;
public Player players[];
public Player temp;
public Team(String inputname, String plays[]) { //THIS METHOD RECEIVES A NULL FOR 'INPUTNAME' AND WHAT APPEARS TO BE A JIBBERISH (ex: Player@5bdf59bd, maybe a memory address?) FOR 'PLAYS[]'
inputname = teamname;
System.out.println(teamname);
players = new Player [plays.length];
for( int k=0 ; k<plays.length ; k++ )
{ System.out.println(inputname);
this.players[k] = new Player(plays[k]);
System.out.println(players[k]);
}
}
public void sortPlayers() {
int n = players.length;
for (int pass=1; pass < n; pass++){
for (int i=0; i < n-pass; i++) {
String playerName = players[i].getLastName();
String nextPlayerName = players[i+1].getLastName();
if(playerName.compareTo(nextPlayerName) > 0)
temp = players[i];
players[i] = players[i+1];
players[i+1] = temp;
}
}
}
}
If anyone could help me figure what is going on here, I'd be very grateful! I've marked the two problematic statements with comments, and a PasteBin of it all can be found below: http://pastebin.com/QGALKbP6
"temp" should not be a member variable, it should be local to the if block in the sort method. and, because if its expanded scope, you are inadvertently clearing some members of your players array due to the fact that your "if" block is missing some braces.
if(playerName.compareTo(nextPlayerName) > 0) {
Player temp = players[i];
players[i] = players[i+1];
players[i+1] = temp;
}
generally, even though braces are optional in some circumstances, you should use them all the time to avoid subtle bugs like this.