0

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!

Yuna Luzi
  • 318
  • 2
  • 9

1 Answers1

1

The Java Virtual Machine (JVM) can only execute code with a main method. 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.

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. Also, as you're only using the console, subclassing ConsoleProgram would be enough.

Nordic88
  • 129
  • 1
  • 12