2010-07-17 3 views
1

나는 printStackTrace에 시도하고 나는이 오류로 인해 ... 정적 (내 생각) ... 그러나, 라인 17 라인 38 문제입니다 모든 것을 coverted 한 :자바 NullPointerException이

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 : 선 (38) anItem.addInv(1);

:

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}; 
    } 
} 
,536,913,632 : 여기 arr.add("Dan");

그리고 내 코드입니다 10

보시다시피 그 선들과 나는 무엇을 해야할지 모르겠다. : \

+0

코드가 엉망입니다. 하나의 아이템만을 나타내는 객체에서'getItem (idx)'를 호출하는 이유는 무엇입니까? 당신은 아이템의 개념과 목록을 혼란스럽게 만들었습니다. – Eric

+1

동의 - OP는 새로운 Java 프로그래머가 될 가능성이 + 우리가 비판보다 지침을 제공하는 것이 더 도움이 될 것입니다. –

답변

1

String canEat = "false"; 왜 문자열로 변환합니까?

클래스와 inventory 클래스를 혼란스럽게 보였습니다.

아마도 열거 더 나은 것 :
public enum InventoryItem 
{ 
    PICKAXE("Pickaxe", "Can be used to mine with", ItemType.Tool, 
      5, 2, 0) 

    EPIC_PICKAXE("Super mega awesome Pickaxe", "Can be used to mine with, but epically", ItemType.Tool, 
      1000000, 100, 0) 


    public static enum ItemType { 
     TOOL, 
     WEAPON 
    } 

    public final String name, description; 
    public final ItemType type; 
    public final boolean canSell, canEat, canEquip; 
    public final int earnedCoins, attackAdd, defenseAdd; 

    private InventoryItem(String name, String description, ItemType type 
          int earnedCoins, int attackAdd, int defenseAdd, 
          boolean canSell, boolean canEat, boolean canEquip) 
    { 
     this.name  = name; 
     this.description = description; 
     this.type  = type 
     this.canSell  = canSell; 
     this.canEat  = canEat; 
     this.canEquip = canEquip; 
     this.earnedCoins = earnedCoins; 
    } 

    private InventoryItem(String name, String description, ItemType type 
          int earnedCoins, int attackAdd, int defenseAdd) 
    { 
     this(name, description, type, 
      earnedCoins, attackAdd, defenseAdd, 
      true, false, true); 
    } 
} 

그런 다음 당신은 당신의 플레이어의 클래스 내 List<InventoryItem> inventory = new ArrayList<InventoryItem>()을 가질 수 있고, 직접 그와 인터페이스.

+0

return 메서드는 한 가지 유형 만 반환하기 때문에. – nn2

+0

그래서 개체를 반환하십시오! – Eric

+0

"regular"클래스는 아마도 enum-enum보다 낫습니다. 영구적으로 고정 된 옵션 세트로 설계되었습니다. –

2

변수 arr이 초기화되지 않았습니다. 주에서

변수 편곡() 함수 addInv()

그냥 그것을 해결하기 위해 addInv에 초기화에 같은 편곡이 아니다.

+0

"또는 main()에서 다시 선언을 제거합니다. arr = new ArrayList();" - 'arr'속성이 main 메소드에서 범위를 벗어 났기 때문에 작동하지 않습니다. 가장 좋은 방법은 생성자에서 'arr'을 초기화하는 것입니다. – chrisbunney

+0

네, 맞습니다. 나는 그것을 제거했다. – Hrishi

2

arr에 add() 메서드를 호출하면 아직 초기화되지 않았기 때문에 NullPointerException이 초기화됩니다.

아마도 다른 방법으로 ArrayList를 사용할 것이므로 생성자에서 초기화해야합니다. 예 :

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

몇 가지 팁 (직접 문제를 해결 않는 한) :

1) 비공개로 변수를 선언, 또는 대부분의 보호 가능한가. 필자는 개인적으로 패키지 수준의 액세스 인 "기본값"을 사용하지 않습니다 (동일한 패키지의 모든 항목에서 볼 수 있음).

2) 불변 값에만 public을 사용하십시오. 변경 불가능한 값은 변경할 수없는 값입니다 (모든 멤버가 최종 결과를 보장하는 가장 좋은 방법이거나 개체가 생성되고 변수가 모두 비공개 인 경우 모든 값이 수정되지 않습니다).

3) 가능할 때마다 항상 변수를 final로 선언하십시오 (클래스 변수, 인스턴스 변수, 매개 변수, 로컬 변수).

여기서 직접적으로 도움이되는 팁은 # 3입니다. "arr"에 값을 지정하지 않았으므로 null입니다. final로 선언했다면 컴파일러는 강제로 값을 할당 할 것입니다. 그렇지 않으면 코드가 컴파일되지 않습니다.

작은 일을하면 프로그래밍을 시작할 때까지 몇 시간을 절약 할 수 있습니다. 제 경우에는 비슷한 것을 했지요. 똑같은 것은 아니 었습니다. (실제로 저는 # 2 종류의 방식을 위반했습니다) 약 1 주일이 걸렸습니다. 나는 15 년 넘게 자바 프로그래밍을 해왔다 ...이런 식으로 일주일을 낭비 할 수 있다면 낭비 할 수있는 시간을 생각해보십시오 .-

관련 문제