2015-01-15 3 views
0

Я получаю ошибку Exception in thread "main" java.lang.NullPointerException в моем коде.JAVA Ошибка двоичного ввода (Исключение в потоке "main" java.lang.NullPointerException)

Предполагается, что это будет симуляция битвы между игроком и монстром. Каждые две недели я получаю задание обновить его новыми функциями. На этой неделе я должен сделать еще одну версию монстра: здесь она получает половину урона от обычных атак и полтора урона от заклинаний. (ChargeMonster.java был другой задачей, но он работает)

Проблема в ResistantMonster.java, но я не знаю, что это такое, поэтому я буду включать весь свой код.

Exception in thread "main" java.lang.NullPointerException 
at ResistantMonster.takeDamage(ResistantMonster.java:12) 
at Character.attack(Character.java:48) 
at Game.main(Game.java:161) 

Код:

public class ResistantMonster extends Monster { 

    public ResistantMonster(int maxHp, int atk, double hitChance) { 
     super(maxHp, atk, hitChance); 
    } 

    public void takeDamage(int damage) { 
     if (input.equals("1")) { // exception occurs here 
      currentHp -= ((int) 0.5 * damage); 
     } else { 
      currentHp -= ((int) 1.5 * damage); 
     if (getCurrentHp() < 0) { 
      currentHp = 0; 
     } 
    } 
} 

public class Game { 

    public static void main(String[] args) { 
     Player player = new Player(150, 30, 60, 3, 0.7, 100, 15); 
     Monster[] monsters = new Monster[5]; 
     for (int i = 0; i < 5; i++) { 
      monsters[i] = new ResistantMonster(100 + (int) (Math.random() * 101), 20 + (int) 
     } 
     Monster monster = monsters[(int) (Math.random() * 5)]; 

     Scanner sc = new Scanner(System.in); 
     String input; 

     int turn = 0; 

     while (player.getCurrentHp() > 0 && monster.getCurrentHp() > 0) { 
      System.out.println("----------------------------------------------------------------"); 
      System.out.println("Round " + turn); 
      System.out.println(player.toString()); 
      System.out.println(monster.toString()); 
      System.out.println("----------------------------------------------------------------"); 
      System.out.println("Possible commands:"); 
      System.out.println("1 -> Attack"); 
      System.out.println("2 -> Item (" + player.getRemainingItemUses() + " remaining)"); 
      System.out.println("3 -> Fire-Spell (AP 50)"); 
      System.out.println("4 -> Water-Spell (AP 40)"); 
      System.out.println("5 -> Thunder-Spell (AP 30)"); 
      System.out.println("Which command??");   

      input = sc.nextLine(); 

      if (input.equals("1")) { 
       turn++; 
       System.out.println("Player attacks!"); 
       if (player.attack(monster) != -1) { //!!!!errorline 
        System.out.println("Player hits!"); 
       } else { 
        System.out.println("Player missed."); 
       } 
      } else if (input.equals("2")) { 
       turn++; 
       if (player.heal(player.getHealingPower())) { 
        System.out.println("Player uses a healing potion."); 
       } else { 
        System.out.println("Player has no more potions."); 
       } 
      } else if (input.equals("3")) { 
       turn++; 
       if (player.spell1(monster)) { 
        System.out.println("Player uses a fire spell!"); 
       } else { 
        System.out.println("Player has not enough ability points left."); 
       } 
      } else if (input.equals("4")) { 
       turn++; 
       if (player.spell2(monster)) { 
        System.out.println("Player uses a water spell!"); 
       } else { 
        System.out.println("Player has not enough ability points left."); 
       } 
      } else if (input.equals("5")) { 
       turn++; 
       if (player.spell3(monster)) { 
        System.out.println("Player uses a thunder spell!"); 
       } else { 
        System.out.println("Player has not enough ability points left."); 
       } 
      } else { 
       turn++; 
       System.out.println("Invalid Command"); 
      } 
      player.regenerateAp(); 

      if (monster.isDefeated()) { 
       break; 
      } 

      System.out.println("Monster attacks!"); 

      int ret = monster.action(player); 
      if (ret >= 0) { 
       System.out.println("Monster hits!"); 
      } else if(ret == -1) { 
       System.out.println("Monster missed."); 
      } else { 
       System.out.println("Monster charges."); 
      } 
     } 

     sc.close(); 
     System.out.println("----------------------------------------------------------------"); 
     System.out.println("Game over in round " + turn); 
     System.out.println(player.toString()); 
     System.out.println(monster.toString()); 
     System.out.println("----------------------------------------------------------------"); 

     if (player.isDefeated()) { 
      System.out.println("Player won!"); 
     } else { 
      System.out.println("Player lost!"); 
     } 
    } 
} 

public class Character { 
    protected int currentHp; 
    protected int atk; 
    protected double hitChance; 

    public Character(int maxHp, int atk, double hitChance) { 
     this.currentHp = maxHp; 
     this.atk = atk; 
     this.hitChance = hitChance; 
    } 

    public void takeDamage(int damage) { 
     currentHp -= damage; 
     if (getCurrentHp() < 0) { 
      currentHp = 0; 
     } 
    } 

    public boolean isDefeated() { 
     if (getCurrentHp() == 0) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public int getAtk() { 
     return this.atk; 
    } 

    public int getCurrentHp() { 
     return this.currentHp; 
    } 

    public int attack(Character target) { 
     if (Math.random() <= hitChance) { 
      int damage = (int) (atk * (Math.random() + 1.0)); 
      target.takeDamage(damage); //!!!!errorline 
      return damage; 
     } else { 
      return -1; 
     } 
    } 

    public String toString() { 
     return "HP " + currentHp + " - ATK " + atk + " - Hit Chance " + hitChance; 
    } 
} 

public class Monster extends Character { 

    public Monster(int maxHp, int atk, double hitChance) { 
     super(maxHp, atk, hitChance); 
    } 

    public int action(Character target) { 
     return attack(target); 
    } 

    public String toString() { 
     return "Monster: HP " + currentHp + " - ATK " + atk + " - Hit Chance " + hitChance; 
    } 
} 

public class ChargeMonster extends Monster { 
    private double chargeChance = 0.2; 

    private boolean charged = false; 

    public ChargeMonster(int maxHp, int atk, double hitChance) { // Konstruktor 
     super(maxHp, atk, hitChance); 
    } 

    public int action(Character target) { 
     if (!charged) { 
      double rdm = Math.random(); 
      if (rdm > chargeChance) { 
       return attack(target); 
      } else { 
       charged = true; 
       return -2; 
      } 
     } else { 
      return attack(target); 
     } 
    } 

    public int attack(Character target) { 
     if (!charged) { 
      if (Math.random() <= hitChance) { 
       int damage = (int) (atk * (Math.random() + 1.0)); 
       target.takeDamage(damage); 
       return damage; 
      } else { 
       return -1; 
      } 
     } else { 
      if (Math.random() <= hitChance) { 
       int damage = (int) (atk * (Math.random() + 2.5)); 
       target.takeDamage(damage); 
       charged = false; 
       return damage; 
      } else { 
       return -1; 
      } 
     } 
    } 
} 

PS: если нужно, я могу скопировать мой Player.java

PS2: пожалуйста, оставьте комментарий о том, как мое кодирование. Любые советы для улучшения были бы действительно потрясающими! Заранее спасибо!

+0

его на самом деле P.P.S. : P –

+0

Перейти на этот сайт, чтобы просмотреть обзор кода: http://codereview.stackexchange.com/ (но ваш код должен работать в первую очередь). – Tom

ответ

2

Согласно вашей ошибке вы пытаетесь получить доступ к нулевому значению. Единственное, что вы видите на отмеченной строке, - input. Поэтому ваша ошибка сообщает вам, что input имеет значение NULL.

Где вы устанавливаете input в классе ResistantMonster? Насколько я могу судить, глядя на ваш код, у вас его нет.

Чтобы исправить это, отправьте input (что я предполагаю, что вы пытались получить доступ) от вашего основного класса до вашего экземпляра ResistantMonster через конструктор или метод takeDamage().

0

Вы делаете довольно ошибку здесь вы объявляете переменный ввод в главном классе и пытаетесь получить к нему доступ в ResistantMonster Это невозможно

Либо вы должны объявить его статическим или вы должны передать его во время вызова метода атаки ResistantMonster.

Спасибо, Himanshu

Смежные вопросы