java - 如何正确使用对象实例的 for 循环 - 我不断收到空指针异常(Java)

标签 java nullpointerexception instance-variables

我仍在学习 Java 的基础知识,所以请耐心等待。我正在创建一个简单的足球模拟器游戏,现在我正在尝试让来自不同国家/地区的玩家填充游戏。

我创建了一个 for 循环来遍历玩家实例化对象的数组,但我不断收到空指针异常。这是我的代码:

public static void main(String[] args) {

        SoccerPlayers[] newPlayer = new SoccerPlayers[5];
        for (int i = 0; i < newPlayer.length; i++){
            newPlayer[i].PlayerCountry();
            newPlayer[i].PlayerPosition();
            newPlayer[i].PlayerName();
            newPlayer[i].PlayerAge();
            newPlayer[i].PrintSoccerPlayer();
        }

    }

我不知道这是我执行 for 循环的方式还是其他类处理该方法的方式,因为它指向使用的第一个方法。以下是其他类的方法示例。

public class SoccerPlayers extends SoccerMain {

    public String playerContinent = "";
    public String playerPosition = "";
    public String playerCountry = "";
    public String playerFirstName = "";
    public String playerLastName = "";
    public String playerName = "";
    public int playerAge = 0;

    public void PlayerCountry(){

        int continent = randomNum.nextInt(6) + 1;
        int country = 0;

        if (continent == 1){
            playerContinent = "North America";
        }else if (continent == 2){
            playerContinent = "South America";
        }else if (continent == 3){
            playerContinent = "Europe";
        }else if (continent == 4){
            playerContinent = "Africa";
        }else if (continent == 5){
            playerContinent = "Asia";
        }else{
            playerContinent = "Oceanica";
        }

        if (playerContinent == "North America"){
            country = randomNum.nextInt(100) + 1;
            if (country > 0 && country < 11){
                playerCountry = "Canada";

最佳答案

创建对象数组时,数组的元素被分配默认值,即 null。 (不要与原语数组的数组混淆。例如:在原语 int 的情况下,默认值将为 0)。

情况 1:对象数组

   SoccerPlayers[] newPlayer = new SoccerPlayers[5];
   // now all elements of newPlayer are null
   System.out.println(newPlayer[0]); // prints null

情况 2:基元数组

   int[] intArr = new int[5];
   // now all elements are initialized to 0 (default value for primitive int)
   System.out.println(intArr[0]); // prints 0

因此,您必须创建新对象并将它们根据需要存储在数组中。

更改此:

 for (int i = 0; i < newPlayer.length; i++){
         // create objects of SoccerPlayers and store them in array
         newPlayer[i] = new SoccerPlayers(); 
         newPlayer[i].PlayerCountry();
         .........
         .........

关于java - 如何正确使用对象实例的 for 循环 - 我不断收到空指针异常(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23281130/

相关文章:

android - setText()不适用于膨胀的布局

java - 是否可以使用 Integer.parseInt(String) 将我们通过 get string extra Intent 获得的字符串值转换为整数

java - 在 Java 中如何使用变量?

objective-c - 未声明的伊瓦尔?

java - GSon是否弄乱了时间戳变量

java - 仅 arraylist 的最后一行保存在 JSON 对象中

尝试访问外部存储(sdcard)上的视频时出现android-get nullpointerexception

java - 抽象类变量和继承

java - 在 Spring 3 中创建单元测试

java - 在界面中从数组中提取统计信息?