java - 从终端使用 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 方面相当新,所以任何关于如何完成这项工作的建议都将不胜感激!
解决方案
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
就足够了。
推荐阅读
- c++ - C++ - 字符串容量模式
- c++ - [[carries_dependency]] 是什么意思以及如何实现
- docker - 如何在 docker-compose 中使用共享卷
- javascript - 如何在 div 或自定义标签属性中调用函数
- html - 去除 :before :after 伪元素中的间隙
- javascript - 我正在尝试打开模式,但前提是用户单击复选框以同意 ToS
- asp.net-mvc - 使用 web api 从一个 localhost 应用程序检索数据到另一个 localhost 应用程序
- asp.net - 从 Asp.Net 网站外部访问 Azure Blob 存储
- python-3.x - 如何对具有其中一列作为版本号的数据框进行排序?
- javascript - 如何在javascript中排序和获取最后一个值和索引