这个问题在这里已有答案:
我试图这样做,以便每当你攻击敌人时,你的剑使用1耐久性,你的剑的伤害取决于剑的耐久性%
问题是它一直说sword.getDamage()= 0.0
主要课程:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
Random random = new Random();
String enemy = null;
String input;
Sword sword = new Sword(1, 10000, "Training Sword");
Dictionary<String, Attributes> OneToTen = new Hashtable<String, Attributes>();
OneToTen.put("Zombie", new Attributes(12, 11, 10, 0, 0, 4, 5, 0));
OneToTen.put("Wizard", new Attributes(5, 6, 4, 15, 15, 10, 10, 10));
OneToTen.put("Spider", new Attributes(7, 7, 7, 4, 6, 15, 16, 3));
int TotalDamageDone = 0;
int enemyNum = random.nextInt(3);
if (enemyNum == 0) {
enemy = "Zombie";
} else if (enemyNum == 1) {
enemy = "Wizard";
} else if (enemyNum == 2) {
enemy = "Spider";
}
System.out.println("Welcome to the Dungeon Of Doom \nYour enemy is a " + enemy + " it has " + (OneToTen.get(enemy).Constitution * 10) + " health. Good Luck!");
System.out.println("What do you want to do?");
System.out.println("I for Inventory, A for Attack, or S for Spell!");
System.out.print(" >>>");
input = in.nextLine();
if (input.equals("A")) {
System.out.println("You hit the " + enemy + " for " + sword.getDamage() + " damage.");
sword.subtractDurability(1);
}
}
}
剑类:
public class Sword {
int BaseDamage;
int BaseDurability;
int Durability;
double DurabilityPercentage;
int Damage;
String Name;
public Sword(int damage, int durability, String name) {
BaseDamage = damage;
BaseDurability = durability;
Durability = BaseDurability;
updateDamage();
Name = name;
}
public void updateDamage() {
DurabilityPercentage = (1 / BaseDurability) * Durability;
Damage = (int) Math.round( (double) (BaseDamage * DurabilityPercentage) + 0.499999);
}
public double getDurability() {
updateDamage();
return DurabilityPercentage;
}
public void subtractDurability(int durability) {
Durability -= durability;
updateDamage();
}
public double getDamage() {
updateDamage();
return Damage;
}
}
属性类只有变量:
大多数变量尚未使用
DurabilityPercentage = (1 / BaseDurability) * Durability;
BaseDurability
是一个int
,所以计算1 / BaseDurability
是用整数算术完成的,它将它截断为0.使1.0
强制浮点运算。
DurabilityPercentage = (1.0 / BaseDurability) * Durability;