我如何使这个'怪物战斗模拟器'工作?

时间:2013-11-04 04:36:07

标签: java class methods simulator

现在,控制台允许我编译,但不能运行它,它说:
“错误:无法找到或加载主类MonsterFight”

以下是代码:

class Fight {

    Random rand= new Random();

    int Hit (int x) {
        int numHit = rand.nextInt(100);
        return (int) x - numHit;
    }


class MonsterFight {
    public void main(String [] args){
        String name;
        int hp = 1000;

        System.out.println("You start at 1000 Hitpoints.");
        Fight battle = new Fight();

        while (hp != 0)  {
            hp = Hit(hp);
            System.out.println("You have now " + hp + " hitpoints.");
        }
    }
}

}

我似乎无法使其发挥作用。所有的帮助表示赞赏,也提示使这个更清洁,也很感激,因为我对Java很新。

2 个答案:

答案 0 :(得分:3)

声明主方法static并使MonsterFight成为顶级类(因为静态方法只能在后者中声明):

class MonsterFight {
    public static void main(String [] args){
      ...
    }
}

答案 1 :(得分:1)

将MonsterFight设为公共外部类,主要方法签名应为

 public static  void main(String [] args){

注意:具有while循环

的适当条件

试试这个

import java.util.Random;

class Fight {
   static  int Hit (int x) {
       Random rand= new Random();
        int numHit = rand.nextInt(100);
        return (int) x - numHit;
    }

}

public class MonsterFight {
    public static  void main(String [] args){
        String name;
        int hp = 1000;

        System.out.println("You start at 1000 Hitpoints.");
        Fight battle = new Fight();

        while (hp != 0)  {
            hp = Fight.Hit(hp);
            System.out.println("You have now " + hp + " hitpoints.");
        }
    }
}