【问题标题】:How do I make this 'monster fight simulator' work?如何使这个“怪物战斗模拟器”工作?
【发布时间】:2013-11-14 17:12:09
【问题描述】:

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

【问题讨论】:

    标签: java class methods simulator


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      将 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.");
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 2016-11-26
        • 1970-01-01
        • 2017-06-23
        相关资源
        最近更新 更多