スッキリわかるJava入門 第8章 インスタンスとクラス(練習問題)
第8章 インスタンスとクラス(練習問題)
練習8(8-1~8-4)
public class Cleric { // 名前 String name; // HP int hp = 50; // 最大HP final int MAX_HP = 50; // MP int mp = 10; // 最大MP final int MAX_MP = 10; // 魔法_セルフエイド public void selfAid() { System.out.println(name + "は魔法「セルフエイド」を唱えた!"); // MPを5消費 this.mp -= 5; // HPを最大HPまで回復 this.hp = this.MAX_HP; System.out.println("最大HPまで回復した."); } // 祈る public int pray(int sec) { System.out.println(name + "は、" + sec + "秒祈った!"); // ランダムで0~2ポイント補正 int correction = new java.util.Random().nextInt(3); System.out.println("** 補正ポイント:" + correction); // MP回復量(仮) int tempAidPoint = sec + correction; // 最大MPより回復しないよう制御 //(MP回復量(仮)またはMP減少値の最小値を採用) int aidPoint = Math.min(tempAidPoint, this.MAX_MP - this.mp); System.out.println("** 回復前のMP:" + this.mp); // MP回復 this.mp += aidPoint; System.out.println("MPが" + aidPoint + "ポイント回復した."); System.out.println("** 回復後のMP:" + this.mp); return aidPoint; } }
public class Main { public static void main (String[] args) { Cleric cleric = new Cleric(); // 名前 cleric.name = "聖職者A"; // 魔法_セルフエイド cleric.selfAid(); // 4秒祈る cleric.pray(4); } }
実行結果①:MP回復量(仮)< MP減少値(4 < 5)
C:\work\ex84>java Main
聖職者Aは魔法「セルフエイド」を唱えた!
最大HPまで回復した.
聖職者Aは、4秒祈った!
** 補正ポイント:0
** 回復前のMP:5
MPが4ポイント回復した.
** 回復後のMP:9
実行結果②:MP回復量(仮)= MP減少値(5 = 5)
C:\work\ex84>java Main
聖職者Aは魔法「セルフエイド」を唱えた!
最大HPまで回復した.
聖職者Aは、4秒祈った!
** 補正ポイント:1
** 回復前のMP:5
MPが5ポイント回復した.
** 回復後のMP:10
実行結果②:MP回復量(仮)> MP減少値(6 > 5)
C:\work\ex84>java Main
聖職者Aは魔法「セルフエイド」を唱えた!
最大HPまで回復した.
聖職者Aは、4秒祈った!
** 補正ポイント:2
** 回復前のMP:5
MPが5ポイント回復した.
** 回復後のMP:10