発生している問題
作成したWizardクラスのhealメソッドを実行したいのですが、実行できません。
発生している問題・エラーメッセージ
Exception in thread "main" java.lang.NullPointerException at Wizard.heal(Wizard.java:13) at Main.main(Main.java:8)
該当のソースコード
Java
1 2 public class Main{ 3 public static void main(String[] args) { 4 Hero h = new Hero("勇者"); 5 Wizard wiz = new Wizard(); 6 Wand wan = new Wand("魔法の杖"); 7 8 wiz.heal(h); 9 } 10 }
public class Wizard{ private int hp; private int mp; private String name; private Wand wand; public void heal(Hero h) { int basePoint = 10; //基本回復ポイント int recovPoint = (int) (basePoint * this.getWand().getPower()); h.setHp(h.getHp() + recovPoint); System.out.println(h.getName() + "のHPを" + recovPoint + "回復しました。"); } public int getHp() { return this.hp; } public void setHp(int h) { if(h < 0) { this.hp = 0; }else { this.hp = h; } } public int getMp() { return this.mp; } public void setMp(int m) { if(m < 0 ) { throw new IllegalArgumentException("MPの値が不正です。"); } this.mp = m; } public String getName() { return this.name; } public void setName(String n) { this.name = n; } public Wand getWand() { return this.wand; } public void setWand(Wand w) { if(w == null) { throw new IllegalArgumentException("杖の名前がありません。"); } this.wand = w; } }
public class Wand { private String name; private double power; Wand(String n){ this.name = n; this.power = 10.0; } public String getName() { System.out.println("名前は" + this.name + "です。"); return this.name; } public void setName(String n) { if(n == null || n.length() < 3) { throw new IllegalArgumentException("杖の名前が適切ではありません。"); } this.name = n; } public double getPower() { return this.power; } public void setPower(double p) { if(p < 0.5 || p > 100) { throw new IllegalArgumentException("杖の魔力が異常です。"); } this.power = p; } }
public class Hero{ private int hp; private String name; Sword sword; static int money; Hero(String n){ name = n; hp = 50; } void bye() { System.out.println("勇者は別れを告げた。"); } private void die() { System.out.println(this.name + "は死んでしまった。"); System.out.println("GAME OVER"); } void sleep() { this.hp = 100; System.out.println(this.name + "は眠って回復した。"); } public String getName() { return this.name; } public void setName(String name) { if(name == null) { throw new IllegalArgumentException ("名前がnullである。処理の中断。"); } if(name.length() <= 1) { throw new IllegalArgumentException ("名前が短すぎる。処理の中断。"); } if(name.length() >= 8) { throw new IllegalArgumentException ("名前が長すぎる。処理の中断。"); } this.name = name; System.out.println("名前を" + this.name + "に変更しました。"); } public int getHp() { return this.hp; } public void setHp(int h) { this.hp = h; } }
試したこと
エラーを調べた結果、インスタンスを生成していないオブジェクトに対して操作を実行しようとした場合にNullPointerExceptionがthrowされるということだったので、すべてのクラスをMainクラスでインスタンス化しましたが実行出来ませんでした。
回答2件
あなたの回答
tips
プレビュー