StringSpacer方法中的空指针异常错误

时间:2014-11-30 18:48:46

标签: java nullpointerexception

我在一年前为学校做了这个项目,这是一个基于文本的口袋妖怪战斗舞台。我几天前打开它来展示一些朋友,我收到了Null Pointer Exception错误。当我在一年前转向它时,它工作得很好,从那以后我没有做任何改变。我已经搞乱了 displayTeam 方法和 stringSpacer 方法,因为基于错误消息,问题似乎来自那里。

以下是我现在收到的错误消息:

Exception in thread "main" java.lang.NullPointerException
at Game.stringSpacer(Game.java:175)
at Game.displayTeam(Game.java:217)
at Game.choosePokemon(Game.java:166)
at PokemonFighter.main(PokemonFighter.java:9)

stringSpacer 方法用于使文本与显示Pokemon团队统计信息的表保持一致。这是 stringSpacer 方法:

   172   public String stringSpacer(String str, int size){
   173   String before="";
   174   String after="";
   175   size-=str.length();
   176   size/=2;
   177   if(str.length()%2!=0){after+=" ";}
   178   for(int i=0;i<size;i++){
   179     before+=" ";
   180     after+=" ";
   181   }
   182   return before+str+after;
   183   }

以下是 displayTeam 方法:

   212  public void displayTeam(Pokemon[] team){
   213      System.out.println("\n|-NUM-|----POKEMON NAME----|--DEX--|--TYPE 1--|--TYPE 2--|--HP--|-SPEED--|-STATUS-|");
   214      for(int i=0; i<team.length;i++){
   215          String fnt="   OK   ";
   216          if(team[i].checkFaint()){fnt=" FAINT! ";}
   217/218          System.out.println("|  "+i+"  |"+stringSpacer(team[i].getName(),20)+"| "+team[i].getDex()+"  |"+stringSpacer(team[i].getType1(),10)+"|"+stringSpacer(team[i].getType2(),10)                     +"|"+stringSpacer(team[i].getHp()+"",6)+"|"+stringSpacer(team[i].getSpeed()+"",8)+"|"+fnt+"|");
   219      }
   220  }

以下是 choosePokemon 方法:

   157   public void choosePokemon(){
   158      displayPokemon();
   159      System.out.println("Please Choose 3 Pokemon:");
   160      playerTeam[0] = new Pokemon(input.next());
   161      playerTeam[1] = new Pokemon(input.next());
   162      playerTeam[2] = new Pokemon(input.next());
   163      chooseOpponent();
   164      cleanSpace();
   165      System.out.println("YOUR TEAM:");
   166      displayTeam(playerTeam);
   167      System.out.println("\n\nOPPONENT'S TEAM:");
   168      displayTeam(comTeam);   
   169   }

宠物小精灵类构造函数和数据字段

     7   private String name, type1, type2, dex, ailment;
     8   private int hp, attack, defense, spAttack, spDefense, speed;
     9   private boolean faint=false;
    10   private int accuracy=100;
    11   private Attack[] moveset;
    12   private Random r = new Random();
    13   
    14   public Pokemon(String id) {
    15     /*
    16      * use Pokedex.txt for pokemon
    17      */
    18     moveset = new Attack[4];
    19     try{
    20         Scanner pokedex = new Scanner(new File("/Final Project/src/PokemonBattle/Pokedex.txt"));
    21        do{       if(pokedex.next().equals(id)){
    22              setDex(id);
    23              setName(pokedex.next());
    24              setType1(pokedex.next());
    25              setType2(pokedex.next());
    26              setHp(pokedex.nextInt());
    27              setAttack(pokedex.nextInt());
    28              setDefense(pokedex.nextInt());
    29              setSpAttack(pokedex.nextInt());
    30              setSpDefense(pokedex.nextInt());
    31              setSpeed(pokedex.nextInt());
    32              setMove(pokedex.next(),0);
    33              setMove(pokedex.next(),1);
    34              setMove(pokedex.next(),2);
    35              setMove(pokedex.next(),3);
    36              break;} 
    37      }while(pokedex.hasNextLine());  
    38      pokedex.close();
    39   }catch(Exception e){}
    40   this.iv();
    41   }

宠物小精灵setType1方法

   193   public void setType1(String type1) {
   194      this.type1 = type1;
   195   }

宠物小精灵setName方法

   185   public void setName(String name) {
   186      this.name = name;
   187   }

宠物小精灵文本文件

#Pokedex Name, Type1, Type2, HP, Attack, Defense, SpAttack, SpDefense, Speed, Attack 1 2 3 4
#Information from Pokemondb.net
000 Default null null 0 0 0 0 0 0 null null null null
003 Venusaur Grass Poison 80 82 83 100 100 80 Earthquake SludgeBomb EnergyBall DoubleEdge
006 Charizard Fire Flying 78 84 78 109 85 100 Inferno Crunch Slash AirSlash
009 Blastoise Water None 79 83 100 85 105 78 HydroPump Bite IceBeam Earthquake
042 Golbat Poison Flying 75 80 70 65 75 90 AirSlash Bite WingAttack PoisonFang
065 Alakazam Psychic None 55 50 45 135 85 120 GigaImpact Psychic Theif ThunderPunch
068 Machamp Fighting None 90 130 80 65 85 55 DynamicPunch ThunderPunch Earthquake Theif
080 Slowbro Water Psychic 95 75 110 100 80 30 Confusion Earthquake ShadowBall Surf
082 Magneton Electric Steel 50 60 95 120 70 70 ZapCanon GigaImpact FlashCannon Tackle
094 Gengar Ghost Poison 60 65 60 130 75 110 ShadowBall Theif DreamEater ShadowClaw
123 Scyther Bug Flying 70 110 80 55 80 105 XScissor AirSlash SteelWing Theif
124 Jynx Ice Psychic 65 50 35 115 95 95 Blizzard Psychic ShadowBall Pound
143 Snorlax Normal None 160 110 65 65 110 30 Crunch GigaImpact IceBeam Earthquake

我想提前感谢大家对我提出的任何意见或建议!

编辑解决方案:文本文件未被读取,因此Pokemon数组中的元素为空。不得不浏览我的课程并将路径从"/PokemonGame/Pokedex.txt"更改为"Pokedex.txt",并将Movedex文件更改为相同的路径。谢谢大家!

2 个答案:

答案 0 :(得分:1)

我试图破译你的代码,但很难用所有不相关的代码。通常最好是提供涉及问题的代码子集,而不是提供整个程序并要求我们解决您的问题。

话虽如此,我发现了问题(至少问题的结束,而不是根)。

您将null传入stringSpacer,就像这样

public String stringSpacer(str = null, int size){
    String before="";
    String after="";
    size-=str.length(); 
    size/=2; 
    if(str.length()%2!=0){after+=" ";}
    for(int i=0;i<size;i++){
        before+=" ";
        after+=" ";
    }
    return before+str+after;
}

因此,当您尝试将str用作String时,如果它实际为null,则会收到空指针异常。

话虽如此,这不是问题的根源。看来,当您初始化Pokemon[] team时,团队中的某些值未正确初始化(它们已设置为null)。

请参阅下文,了解正在进行的操作示例:

public void displayTeam(Pokemon[] team){
    System.out.println("\n|-NUM-|----POKEMON NAME----|--DEX--|--TYPE 1--|--TYPE 2--|--HP--|-SPEED--|-STATUS-|");
    for(int i=0; i<team.length;i++){
        String fnt="   OK   ";
        if(team[i].checkFaint()){fnt=" FAINT! ";}
        System.out.println("|  "+i+"  |"+stringSpacer(null,20)+"|  "+team[i].getDex()+"  |"+stringSpacer(null,10)+"|"+stringSpacer(null,10)
                +"|"+stringSpacer(null +"",6)+"|"+stringSpacer(null +"",8)+"|"+fnt+"|");
    }
}

我知道传递给stringSpacer的所有值都不是null,但其中一个是。因此,我认为你的问题在于你的口袋妖怪课程。没有那个代码,很难说。

答案 1 :(得分:0)

你可以避免它:

public String stringSpacer(String str, int size){
    if (str == null) return "";
...

或修复team[i].getType1()team[i].getType2()

的空值

您也可以使用"null"将其转换为+""

        System.out.println("|  "+i+"  |"+stringSpacer(team[i].getName(),20)+"|  "+team[i].getDex()+"  |"+stringSpacer(team[i].getType1() + "",10)+"|"+stringSpacer(team[i].getType2() + "",10)
                +"|"+stringSpacer(team[i].getHp()+"",6)+"|"+stringSpacer(team[i].getSpeed()+"",8)+"|"+fnt+"|");