I can see that this question has been asked before, but I have not found previous answers useful - specifically my issue is following Princeton University's 'Algorithms' course on Coursera here and using their algs4.jar file to access ostensibly necessary utilities. I have never used Java before but this seemed like such a good course, I'm trying to muddle through rather than switching to a 'worse' course in a language I know. I have also found a thread specifically on this issue here and a Reddit question here, which were equally as useless as the other questions which had this problem, but not with the Princeton's algs4.jar file.
This is my code, I haven't bothered to finish it but it should run. Before anybody asks, I've commented out everything except the first if (StdIn.isEmpty()) check and it still gives me all the same compiler/interpreter errors, so this is nothing to do with it being half-finished - StdIn.isEmpty() and StdIn.readString() are supposed to be provided by algs4.jar:
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
class RandomWord
{
public static void main(String[] args)
{
if (StdIn.isEmpty())
{
System.out.println("Nothing to read.");
return;
}
String curr_selected_word;
double curr_probability = 0.0;
int i = 0;
while (!StdIn.isEmpty())
{
String current_string = StdIn.readString();
System.out.println("> " + current_string);
}
}
}
Following the advice of previous threads, I compile like this:
javac -cp "./algs4.jar" RandomWord.java
Which works fine. Running java RandomWord, I get this large messy error:
Exception in thread "main" java.lang.NoClassDefFoundError: edu/princeton/cs/algs4/StdIn
at RandomWord.main(RandomWord.java:13)
Caused by: java.lang.ClassNotFoundException: edu.princeton.cs.algs4.StdIn
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more
The accepted answer on the other question was to reference the .jar file explicitly, like this:
java -cp "C:\Coursera\Algorithms\Part 1\Java Solutions\HelloWorld;C:\Coursera\Algorithms\Part 1\Java Solutions\algs4.jar" RandomWord
Which gives me the exact same error. There is also a comment on the Reddit thread that uses the -classpath instead of -cp flag, which at least gives a different but stranger error:
>java -classpath ./algs4.jar RandomWord
Error: Could not find or load main class RandomWord
Caused by: java.lang.ClassNotFoundException: RandomWord
Putting quotes around the .jar filepath, or providing the absolute filepath, all produce the same error.
I Googled this and predictably it is caused by not having a main entry-point, but... see code above?
Lastly, the installer for the Coursera course apparently installs some Bash commands (see here) called javac-algs4 and java-algs4 which is supposed to sort out all this classpath nonsense for me. So I crack open Bash, and:
>javac-algs4 RandomWord.java
'javac-algs4' is not recognized as an internal or external command,
operable program or batch file.
I have restarted since running the installer. I would add these to my PATH manually, but I don't even know where they are; the C:\Program Files\LIFT-CS folder that their installer installs into only contains a pissing uninstaller. So I'm absolutely losing my rag and at my wits' end after spending over 7 hours just trying to start this course, not even getting stuck on the problems or the content. When will content creators learn we don't want your in-house IDE with no dark mode and libraries that do nothing but rename every function to camel-case?
Anyway, if anyone has encountered this or knows what I could do to fix it, help would be appreciated.
You can try this -
javac -cp .;<insert class path> RandomWord
I was facing the exact same issue, I ran javac -cp .;.lift/algs4.jar RandomWord and it works. (My compiled class was in the same directory as .lift)
This worked for me on a Mac. Copy algs4.jar to the root of your project, then:
javac -cp ".:./algs4.jar" RandomWord.java
java -cp ".:./algs4.jar" RandomWord
I'm trying to understand the inclusion of third party jar files in a java project using only the command line in Windows 10.
Specifically, I try to include the file json-20200518.jar in my "project" so that I can use the java object JSONObject in the project.
My java file:
package com.mypackage.example;
import org.json.JSONObject;
class Example {
public static void main(String[] args) {
// ... program logic
}
}
location of my java file (Examp.java):
./com/mypackage/example
location of jar file:
./jars
using cmd win10 I compile:
javac -cp "C:\Users\pfort\Desktop\java\jars\json-20200518.jar" "C:\Users\pfort\Desktop\java\com\mypackage\example\Examp.java"
compilation is successful.
Run:
java -cp "C:\Users\pfort\Desktop\java\jars\json-20200518.jar" com.mypackage.example.Examp
I get a report:
Error: Could not find or load main class com.mypackage.example.Pokus
Caused by: java.lang.ClassNotFoundException: com.mypackage.example.Pokus
Second attempt:
java -cp "C:\Users\pfort\Desktop\java\jars\json-20200518.jar" "C:\Users\pfort\Desktop\java\com\mypackage\example\Pokus"
But the same error message comes back to me.
Where am I going wrong? Is it the wrong structure? I don't get it, the compilation is successful but the run does not work.
The compiled Examp.class file isn't part of json-20200518.jar, so you'll need to add the directory containing it to the command line. Assuming it's the current directory (.):
java -cp "C:\Users\pfort\Desktop\java\jars\json-20200518.jar;." com.mypackage.example.Examp
Ive been trying to test a simple project written by some students. Im testing it on Ubuntu and the project requires me to use ANTLR and a Makefile.
It has been a nightmare to find a configuration of makefile, files and folders that compiles and executes successfully.
So basically this is the folder/file setup:
Makefile
test.txt
laboratorio/
lab02/
Main.java
Lab02.g
The contents of Main.java are fairly simple. They just read the grammar token by token:
package laboratorios.lab02;
import org.antlr.v4.runtime.*;
public class Main{
public static void main(String[] args) throws Exception{
try{
Lab02 lexer = new Lab02(new ANTLRFileStream(args[0]));
while (lexer.nextToken().getType() != Token.EOF);
}catch(ArrayIndexOutOfBoundsException aiobe){
System.err.println("Must provide a valid path to the filename with the tokens");
System.exit(1);
}catch(Exception e){
System.err.println("Must provide a valid path to the filename with the tokens");
System.exit(1);
}
}
}
The contents of Lab02.g (the grammar) are irrelevant for the problem, but it produces a Lab02.java file (with package laboratorios.lab02) that must be compiled and referenced by the Main.java file.
The problem came when trying to test the makefile on Ubuntu. With every configuration I tried I kept getting errors (when compiling or running the Main java file) like:
java.lang.NoClassDefFoundError: org/antlr/v4/runtime/CharStream
Could not find or load main class org.antlr.v4.Tool
Error: Could not find or load main class
Ive followed the exact steps of this tutorial to set up antlr on my pc: Getting Started with ANTLR v4
After many unsuccessful attempts I arrived at this magical configuration that made the whole project work nicely.
Makefile:
make: gramatica main
gramatica: laboratorios/lab02/Lab02.g
java org.antlr.v4.Tool laboratorios/lab02/Lab02.g
main: laboratorios/lab02/Lab02.java laboratorios/lab02/Main.java
javac laboratorios/lab02/Lab02.java laboratorios/lab02/Main.java
run: laboratorios/lab02/Main.class
java -cp ${CLASSPATH}:Lab02.class laboratorios/lab02/Main test.txt
clean:
rm -rf laboratorios/lab02/*.tokens
rm -rf laboratorios/lab02/*.class
rm -rf laboratorios/lab02/Lab02.java
rm -rf laboratorios/lab02/*~
I required me to set the CLASSPATH in the bashrc like this:
export CLASSPATH=.:~/your/path/to/antlr/antlr-4.2-complete.jar
As you would find in the tutorial I previously mentioned (Getting Started with ANTLR v4), it says you should write the Classpath using quotes. COMPLETELY IGNORE THAT ADVICE! Whenever I used quotes the main class wouldnt run as ANTLR was 'missing'. Also, the aliases in the tutorial are completely optional.
Some other things worth pointing out are that placing the Makefile inside the laboratorio/lab02/ folder was not helping either. Moving it out and referencing the java files from the outside helped A LOT. And the characters ".:" helped to execute the Main class as it would say it couldn't been found.
I have create java application using sikuli-script(latest version 1.0.1).
I added the sikuli-script.jar to the Referenced Libraries (I configured using this answer Answer Link)
java code folder structure -->
Java code -->
package com.example.sikuli;
import org.sikuli.script.*;
import java.util.concurrent.TimeUnit;
public class TestSikuli {
public static void main(String[] args) {
Screen s = new Screen();
App app = new App("C:/Program Files/Mozilla Firefox/firefox.exe");//firefox path
try{
app.focus();
TimeUnit.SECONDS.sleep(2);
s.click("imgs/1391152193781.png", 0);//url bar image
s.type(null, "http://www.google.lk", 0);
s.click("imgs/1391152289812.png", 0);//click search image
}
catch(FindFailed e){
e.printStackTrace();
}
}
}
After that i set the the Run Configutrtion such as PATH and SIKULI_HOME
Next I run the code it's working properly.
Then I create .exe using launch4j and according to this site instructions --> How to Create an Executable File from Eclipse
After that i run the .exe file from command prompt then following errors occurred. Please help me.
Error -->
[error] ResourceLoaderBasic: check: libs dir is empty, has wrong content or is outdated
[action] ResourceLoaderBasic: check: Please wait! Trying to extract libs to: C:\Documents and Settings\Dell\SikuliX\libs
[error] ResourceLoaderBasic: loadLib: Fatal Error 109: not found: C:\Documents and Settings\Dell\SikuliX\libs\VisionProxy.dll
[error] Terminating SikuliX after a fatal error(109)! Sorry, but it makes no sense to continue!
If you do not have any idea about the error cause or solution, run againwith a Debug level of 3. You might paste the output to the Q&A board.
--1. when programming in Java using Sikuli, you should always use sikuli-java.jar (sikuli-ide.jar contains much stuff not needed here).
--2. Set a JVM option -Dsikuli.Debug=3 when running the exe to get more details about what's going on. I guess the problem is, that for some reason the export of the native libs does not work in the context of a launch4J exe (I did not test this yet).
--3. always use the latest version (1.1.1 in this case, still nightly but pre-final ;-) http://sikulix.com
This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 7 years ago.
I am having trouble compiling and running my Java code, intended to allow me to interface Java with a shared object for Vensim, a simulation modeling package.
The following code compiles without error:
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
However, when I try to run the following:
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
I get the following error: "Error: Could not find or load main class SpatialModel
". My SpatialModel.java code does contain a 'main' method (below), so I'm not sure what the problem is - can anyone please help me out? Thanks.
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
public class SpatialModel {
private VensimHelper vh;
public static final String DLL_LIBNAME_PARAM = "vensim_lib_nam";
public static final String MODEL_PATH_PARAM = "vensim_model_path";
private final static int VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT = 10;
public SpatialModel() throws SpatialException {
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if(libName == null || libName.trim().equals("")) {
log.error("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
throw new SpatialException("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
}
if(modelPath == null || modelPath.trim().equals("")) {
log.error("Model path has to set with -D" + MODEL_PATH_PARAM);
throw new SpatialException("Model path ahs to be set with -D" + MODEL_PATH_PARAM);
}
for (int i = 0; i < VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT && vh == null; i++) {
try {
log.info("creating new vensim helper\n\tdll lib: " + libName + "\n\tmodel path: " + modelPath);
vh = new VensimHelper(libName, modelPath);
} catch (Throwable e) {
log.error("An exception was thrown when initializing Vensim, try: " + i, e);
}
}
if (vh == null) {
throw new SpatialException("Can't initialize Vensim");
}
}
public static void main(String[] args) throws VensimException {
long before = System.currentTimeMillis();
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if (libName == null) {
libName = "libvensim";
}
if(modelPath == null) {
modelPath = "~/BassModel.vmf";
}
System.setProperty(DLL_LIBNAME_PARAM, libName);
System.setProperty(MODEL_PATH_PARAM, modelPath);
if (args.length > 0 && args[0].equals("info")) {
System.out.println(new VensimHelper(libName, modelPath).getVensimInfo());
} else if (args.length > 0 && args[0].equals("vars")) {
VensimHelper helper = new VensimHelper(libName, modelPath);
String[] vars = helper.getVariables();
for (String var : vars) {
System.out.println(helper.getVariableInfo(var));
}
} else {
File f = new File(".");
System.out.println(f.getAbsolutePath());
SpatialModel sm = new SpatialModel();
}
System.out.println("Execution time: " + (System.currentTimeMillis() - before));
}
}
You must ensure that you add the location of your .class file to your classpath. So, if its in the current folder, add . to your classpath.
Note that the Windows classpath separator is a semi-colon, i.e. a ;.
If the class is in a package
package thepackagename;
public class TheClassName {
public static final void main(String[] cmd_lineParams) {
System.out.println("Hello World!");
}
}
Then calling:
java -classpath . TheClassName
results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:
java -classpath . thepackagename.TheClassName
And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.
To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.
Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”
You can try these two when you are getting the error: 'could not find or load main class'
If your class file is saved in following directory with HelloWorld program name
d:\sample
java -cp d:\sample HelloWorld
java -cp . HelloWorld
I believe you need to add the current directory to the Java classpath
java -cp .:./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
You have to include classpath to your javac and java commands
javac -cp . PackageName/*.java
java -cp . PackageName/ClassName_Having_main
suppose you have the following
Package Named: com.test
Class Name: Hello (Having main)
file is located inside "src/com/test/Hello.java"
from outside directory:
$ cd src
$ javac -cp . com/test/*.java
$ java -cp . com/test/Hello
In windows the same thing will be working too, I already tried
If you work in Eclipse, just make a cleanup (project\clean.. clean all projects) of the project.
You have to set the classpath if you get the error:
Could not find or load main class XYZ
For example:
E:\>set path="c:\programfiles\Java\jdk1.7.0_17\bin"
E:\>set classpath=%classpath%;.;
E:\>javac XYZ.java
E:\>java XYZ
I got this error because I was trying to run
javac HelloWorld.java && java HelloWorld.class
when I should have removed .class:
javac HelloWorld.java && java HelloWorld
Check your BuildPath, it could be that you are referencing a library that does not exist anymore.
If you're getting this error and you are using Maven to build your Jars, then there is a good chance that you simply do not have your Java classes in src/main/java/.
In my case I created my project in Eclipse which defaults to src (rather than src/main/java/.
So I ended up with something like mypackage.morepackage.myclass and a directory structure looking like src/mypackage/morepackage/myclass, which inherently has nothing wrong. But when you run mvn clean install it will look for src/main/java/mypackage/morepackage/myclass. It will not find the class but it won't error either. So it will successfully build and you when you run your outputted Jar the result is:
Error: Could not find or load main class mypackage.morepackage.myclass
Because it simply never included your class in the packaged Jar.
I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
If you try to run a java application which needs JDK 1.6 and you are trying to run on JDK 1.4, you will come across this error. In general, trying to run a Java application on old JRE may fail. Try installing new JRE/JDK.
Problem is not about your main function. Check out for
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
output and run it.
Project > Clean and then make sure BuildPath > Libraries has the correct Library.
java -verbose:class HelloWorld might help you understand which classes are being loaded.
Also, as mentioned before, remember to call the full qualified name (i.e. include package).
I was using Java 1.8, and this error suddenly occurred when I pressed "Build and clean" in NetBeans. I switched for a brief moment to 1.7 again, clicked OK, re-opened properties and switched back to 1.8, and everything worked perfectly.
I hope I can help someone out with this, as these errors can be quite time-consuming.
This problem occurred for me when I imported an existing project into eclipse. What happens is it copied all the files not in the package, but outside the package. Hence, when I tried run > run configurations, it couldn't find the main method because it was not in the package. All I did was copy the files into the package and Eclipse was then able to detect the main method. So ultimately make sure that Eclipse can find your main method, by making sure that your java files are in the right package.
If so simple than many people think, me included :)
cd to Project Folder/src/package there you should see yourClass.java then run javac yourClass.java which will create yourClass.class then cd out of the src folder and into the build folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows
If you are using Eclipse... I renamed my main class file and got that error. I went to "Run As" configurator and under the class path for that project, it had listed both files in the class path. I removed old class that I renamed and left the class that had the new name and it compiled and ran just fine.
This solved the issue for me today:
cd /path/to/project
cd build
rm -r classes
Then clean&build it and run the individual files you need.
I have a similar problem in Windows, it's related to the classpath. From the command line, navigate until the directory where it's located your Java file (*.java and *.class), then try again with your commands.
I use Anypoint Studio (an Eclipse based IDE). In my case everything worked well, until I found out that while running the java code, something totally different is executed. Then I have deleted the .class files. After this point I got the error message from this question's title. Cleaning the project didn't solve the problem.
After restarting the IDE everything worked well again.