0

就目前而言,控制台允许我编译,但不能运行它,它说:
“错误:无法找到或加载主类 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 还很陌生。

4

2 回答 2

3

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

class MonsterFight {
    public static void main(String [] args){
      ...
    }
}
于 2013-11-04T04:37:15.487 回答
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.");
        }
    }
}
于 2013-11-04T04:38:13.607 回答