数据不能在类之间正确传输;导致NullPointerException

时间:2012-03-29 02:27:50

标签: java class nullpointerexception transfer

我最近发布了一个关于在调用对象数组时获取NullPointerException的问题。我已经将问题追溯到提供数据的主要方法与接收数据的相关方法(Team.sortPlayers())之间的某些脱节。

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

如果有人能帮我弄清楚这里发生了什么,我将非常感激!我用注释标记了两个有问题的语句,并且可以在下面找到它的PasteBin: http://pastebin.com/QGALKbP6

1 个答案:

答案 0 :(得分:2)

“temp”不应该是成员变量,它应该是sort方法中if块的本地变量。并且,因为如果它扩大了范围,你会无意中清除你的玩家阵列的某些成员,因为你的“if”区块缺少一些大括号。

        if(playerName.compareTo(nextPlayerName) > 0) {
          Player temp = players[i];
          players[i] = players[i+1];
          players[i+1] =  temp;
        }

一般来说,即使大括号在某些情况下是可选的,你也应该一直使用它们来避免像这样的细微错误。