【发布时间】:2016-01-22 03:43:58
【问题描述】:
我开始着手我的第一个 java 项目,它是某种非常基本的角色扮演游戏(当然没有 gui)。现在我正在研究咒语。我创建了“法术”类(包括名称、效果和成本)。我创建了 SpellsList 类,它应该包括所有的咒语。我有描述法术效果的“效果”类(现在只是为了测试)。当施法者施法时,我想获得相关的法术效果,所以相关的效果会处理法术的效果(我稍后会处理效果,现在只是为了测试)。我有一个掷骰子,但现在没关系。
我有几个问题:
- 代码有什么问题?
- 为什么“public static void main(String[] args) {”很重要?
-
你会以更好的方式实施这些咒语吗?
public class Spell { private String name; private String effect; private int cost; Spell(String name, String effect, int cost){ this.name = name; this.effect = effect; this.cost = cost; } String getSpellName(){ return name; } String getEffect(){ return effect; } int getCost(){ return cost; }}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SpellsList {
public static void main(String[] args) {
List<Spell> spellsList = new ArrayList<Spell>();
spellsList.add(new Spell("Fireball", "damage", 5));
spellsList.add(new Spell("Ice Storm", "damage", 8));
spellsList.add(new Spell("Heal", "heal", 8));
static String getSpellEffect(String spellName) {
for (Iterator iter = spellsList.iterator(); iter.hasNext(); ) {
if (iter.next().equals(spellName)) {
iter.next().Spell.getEffect();
break;
}
}
}
}
}
public class Effects {
int damage(int n, int dice, int bonus){
int damage = Dice.roll(n,dice,bonus);
System.out.println("You dealt" + damage + "damage to the enemy!");
return damage;
}
int heal(int n, int dice, int bonus){
int heal = Dice.roll(n,dice,bonus);
System.out.println("You healed" + heal + " hit points!");
return heal;
}
}
public class Dice {
public static int roll(int dice){
int sum = 1 + (int)(Math.random() * ((dice - 1) + 1));
return sum;
}
public static int roll(int n, int dice){
int sum = 0;
for (int i = 0; i < n; i++) {
sum += 1 + (int)(Math.random() * ((dice - 1) + 1));
}
return sum;
}
public static int roll(int n, int dice, int bonus){
int sum = 0;
for (int i = 0; i < n; i++) {
sum += 1 + (int)(Math.random() * ((dice - 1) + 1));
}
return (sum + n*bonus);
}
}
【问题讨论】:
-
有什么问题?而“public static void main(String[] args) {”是程序的入口点,你必须从某个地方开始。
-
现在代码有什么错误\问题?运行时会发生什么?
-
您的代码中
{和}的数量不平衡。尝试正确缩进(使用 IDE 或任何其他可以为您缩进代码的编辑器)。 -
也许这里有些 { 迷路了,在我的代码中没问题。问题是getSpellEffect,我在声明行非法开始表达,在这个方法中,spellsList和Spell显示为红色