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.
I'm fairly new at working with Java so any advice on how to make this work would be greatly appreciated!
The Java Virtual Machine (JVM) can only execute code with a
mainmethod. Code cannot be executed without amainmethod but it can still be compiled (as you noticed), thus it is mandatory to use amainmethod or you will run intojava.lang.ClassNotFoundException.Simply add this to your code (you don't need the comments):
Btw, since you're overriding
Program#run()you need to add@Overrideas annotation. Also, as you're only using the console, subclassingConsoleProgramwould be enough.