gpt4 book ai didi

Java 空指针异常

转载 作者:行者123 更新时间:2023-11-29 07:21:46 24 4
gpt4 key购买 nike

我尝试了 printStackTrace 并将所有内容都隐藏为静态(我认为)...但是,第 17 行和第 38 行是问题...因为这个错误:

You picked up: Pickaxe
java.lang.NullPointerException
at item.addInv(item.java:38)
at item.main(item.java:17)
Description: Can be used to mine with.
Press any key to continue . . .

第 17 行:anItem.addInv(1);

第 38 行:arr.add("Dan");

这是我的代码:

import java.io.*;
import java.util.*;
import javax.swing.*;

public class item
{
public static int attack, defense;
public static ArrayList<String> arr;
public static String name, desc, typeOf, attackAdd, defenseAdd, canSell, canEat,earnedCoins,canEquip;

String stats[];

public static void main(String args[])
{
item anItem = new item();
ArrayList<String> arr = new ArrayList<String>();
anItem.addInv(1);
}

public static void addInv(int e) {
String iname = getItem(1)[0];
String idesc = getItem(1)[1];
int itypeOf = Integer.parseInt(getItem(1)[2]);
int iattackAdd = Integer.parseInt(getItem(1)[3]);
int idefenseAdd = Integer.parseInt(getItem(1)[4]);
boolean icanSell = Boolean.parseBoolean(getItem(1)[5]);
boolean icanEat = Boolean.parseBoolean(getItem(1)[6]);
int iearnedCoins = Integer.parseInt(getItem(1)[7]);

attack = attack + iattackAdd;
defense = defense + idefenseAdd;
System.out.println("You picked up: " + iname);
try {
arr.add("Dan");
} catch(NullPointerException ex) {
ex.printStackTrace();
}

System.out.println("Description: " + idesc);
}

public static String[] getItem(int e) {

String[] stats = new String[7];

String name = "Null";
String desc = "None";
String typeOf = "0";
String attackAdd = "0";
String defenseAdd = "0";
String canSell = "true";
String canEat = "false";
String earnedCoins = "0";

if (e == 1) {
name = "Pickaxe";
desc = "Can be used to mine with.";
typeOf = "2";
attackAdd = "2";
earnedCoins = "5";
}

return new String[] { name, desc, typeOf, attackAdd, defenseAdd, canSell, canEat, earnedCoins};
}
}

如您所见,就是那些行,我不知道该怎么做...:\

最佳答案

当您在 arr 上调用 add() 方法时,它尚未初始化,因此会出现 NullPointerException。

由于您可能还会在其他方法中使用 ArrayList,因此您应该在构造函数中对其进行初始化;即:

public item() {
arr = new ArrayList<String>();
}

关于Java 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3273384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com