0

I feel I need to declare that I am new to Java. I have read various Stack Overflow posts on how to call non-static methods in my main method. I believe the answers I have found are correct, but when attempting to compile and run my program, I keep running into the error:

"Error: Could not find or load main class HelloWorld Caused by: java.lang.ClassNotFoundException: HelloWorld"

To explain a little more. I am completing a Coursera Java Specialization through Duke. However, I do not want to use the Blue J IDE and I am just running it with VIM instead (I just like the plain editor). I know it is easier to use IDEs, but I would rather know what I am doing (eventually) than be reliant on too many external programs.

The pre-configured BlueJ from Duke comes with the edu.duke libraries pre-configured, however, I have to manually do this myself. I have made use of the following commands when attempting to run the file:

javac -cp "./courserajava.jar" HelloWorld.java (No problems here).

java -cp "./courserajava.jar" HelloWorld (Error arises here).

I am new to creating instances of Objects for non-static methods, but from the other forums it appears as though what I have included below is correct.

The courserajava.jar file is located in the same directory as my HelloWorld.java file.

The file structure may be seen in the below screenshot:

Directory File structure

Then code for my HelloWorld.java file:

import edu.duke.*;

public class HelloWorld {

    public static void main(String args[]) {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.runHello();
    }

    public void runHello() {
        FileResource res = new FileResource("hello_unicode.txt");
        for (String line : res.lines()) {
            System.out.println(line);
        }
    }
}

I promise I have read about 20 forums and cannot seem to get my file to run (I have other more "complicated" projects in java I actually need to run but I have not worked with compilers much hence I decided to just use this simple HelloWorld practice example).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You're including only the jar in your classpath, so it's trying to find the `HelloWorld` class from there. Include the current directory as well (also consider putting your class inside a package) with `-cp ./courserajava.jar;. HelloWorld`. – Kayaman Apr 02 '22 at 10:27
  • Or if you're on Linux `-cp ./courserajava.jar:. HelloWorld` – Mark Rotteveel Apr 02 '22 at 11:00
  • Perfect. literally what I was looking for. Thanks so much! Sorry for the noob question. I did not manage to find the attached link on "How to run a java class with a jar in the classpath". I am fairly new to posting. Some way to accept it as the accepted answer or should I just delete my post and do the walk of shame :D? – NotReallyOliverTwist Apr 02 '22 at 14:12

0 Answers0