繁体   English   中英

从终端使用acm.program包运行Java脚本

[英]Run java script utilizing acm.program package from terminal

我试图在我的终端上运行以下脚本( 此处为代码源)

import acm.program.*;

public class Add2 extends Program {

   public void run() {
      println("This program adds two numbers.");
      int n1 = readInt("Enter n1: ");
      int n2 = readInt("Enter n2: ");
      int total = n1 + n2;
      println("The total is " + total + ".");
   }
} 

然后,在终端上使用以下两个步骤编译并运行代码:

javac -classpath acm.jar Add2.java
java Add2

编译没有错误,但是当我尝试运行脚本时,出现以下错误: Error: Could not find or load main class Add2 我在使用Java方面还很陌生,所以任何有关如何进行此工作的建议将不胜感激!

Java虚拟机(JVM)只能使用main方法执行代码。 没有main方法就无法执行代码,但是仍然可以编译(如您所注意到的),因此必须使用main方法,否则您将遇到java.lang.ClassNotFoundException

只需将其添加到您的代码中(您不需要注释):

public static void main(String[] args) {
    // This class is mandatory to be executed by the JVM.
    // You don't need to do anything in here, since you're subclassing ConsoleProgram,
    // which invokes the run() method.
}

顺便说一句,由于您要覆盖Program#run() ,因此需要添加@Override作为注释。 另外,由于您仅使用控制台,因此子类化ConsoleProgram就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM