首页 > 解决方案 > 从终端使用 acm.program 包运行 java 脚本

问题描述

我正在尝试在我的终端上运行以下脚本 -这里的代码源:

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 方面相当新,所以任何关于如何完成这项工作的建议都将不胜感激!

标签: javaterminalacm-java-libraries

解决方案


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就足够了。


推荐阅读