[英]Run java script utilizing acm.program package from terminal
I am trying to run the following script - source of code here - on my 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 + ".");
}
}
I then compile and run the code using these two steps on my terminal: 然后,在终端上使用以下两个步骤编译并运行代码:
javac -classpath acm.jar Add2.java
java Add2
The compilation indicates no errors , but when I try to run the script, I get the following error: Error: Could not find or load main class Add2
. 编译没有错误,但是当我尝试运行脚本时,出现以下错误:
Error: Could not find or load main class Add2
。 I'm fairly new at working with Java so any advice on how to make this work would be greatly appreciated! 我在使用Java方面还很陌生,所以任何有关如何进行此工作的建议将不胜感激!
The Java Virtual Machine (JVM) can only execute code with a main
method. Java虚拟机(JVM)只能使用
main
方法执行代码。 Code cannot be executed without a main
method but it can still be compiled (as you noticed), thus it is mandatory to use a main
method or you will run into java.lang.ClassNotFoundException
. 没有
main
方法就无法执行代码,但是仍然可以编译(如您所注意到的),因此必须使用main
方法,否则您将遇到java.lang.ClassNotFoundException
。
Simply add this to your code (you don't need the comments): 只需将其添加到您的代码中(您不需要注释):
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.
}
Btw, since you're overriding Program#run()
you need to add @Override
as annotation. 顺便说一句,由于您要覆盖
Program#run()
,因此需要添加@Override
作为注释。 Also, as you're only using the console, subclassing ConsoleProgram
would be enough. 另外,由于您仅使用控制台,因此子类化
ConsoleProgram
就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.