Im using Java SDK 1.7 on Windows 7 via cmd.exe . Up until a few hours ago everything was working correctly when suddenly I was unable to run my compiled class files, consistently presented with the error in the title.
I seem to be able to compile my My.java file however I am unable to run the resulting class file (My.class). I am constantly given the error "Error: Could not find or load main class My.class". I have tried this with multiple other class files all resulting in the same problem.
My 'Path' environment variable is set to "C:\Program Files (x86)\Java\jdk1.7.0_05\bin" if you were wondering
I have tried reinstalling, creating and setting a classpath variable (no luck), and even directly using the
java -cp . My.class
command.
I have tried these posts all to no avail, hence why I'm posting:
Error: Could not find or load main class
Error: Could not find or load main class- Novice
Could not find or load main class
Java 1.7.0_03 Error: Could not find or load main class
If it makes any difference my code is :
import javax.swing.JOptionPane;
class My {
public static void main(String[] args) {
final double x = 3.2;
int i = (int)x;
double m = 0;
if (x < 4) {
String saySomething = JOptionPane.showInputDialog(i);
System.out.println(saySomething);
}
else {
String saySomething = JOptionPane.showInputDialog(i);
System.out.println("Hello World");
}
while (m < 10) {
System.out.print(" While Loop ");
m++;
};
for (i=1; i < 10; i++) {
System.out.println("For Loop");
};
}
}
You should specify the classname instead of the file of the class to load. The difference is a simple matter of removing the .class extension.
I would use an IDE and you shouldn't get these issues. Compile and run is just a click of the mouse.
BTW to run your program from the command line
java -cp . My
You don't add .class
Position yourself in a directory of your project (you need to have src and bin directories there, assuming you keep sources in src and binaries in bin)
java -cp bin My
I myself was facing the same problem. It was happening because I was being remiss in typing the name of the class properly. In my instance, I was typing
java doubler
instead of
java Doubler
Related
I am setting up a java framework that should use the Google OR-Tools. The code below compiles successfully, but throws an exception at runtime:
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.google.ortools.linearsolver.operations_research_linear_solverJNI.MPSolver_CLP_LINEAR_PROGRAMMING_get()I
at com.google.ortools.linearsolver.operations_research_linear_solverJNI.MPSolver_CLP_LINEAR_PROGRAMMING_get(Native Method)
at com.google.ortools.linearsolver.MPSolver$OptimizationProblemType.<clinit>(MPSolver.java:221)
at Main.main(Main.java:15)
I am using Intellij 2018.3 on Windows 10. I spent a lot of time trying to get this run, but unsuccessful. Based on what I found on the internet, the exception might be caused by poor linking and/or missing external libraries on which OR-Tools depends. However, I don't have the background to resolve this issue, and also Intellij does not highlight anything. Any idea what the problem is?
For completion, this is the code I run:
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
public final class Main {
public static void main(String[] args) {
// Create the linear solver with the GLOP backend.
MPSolver solver =
new MPSolver("SimpleLpProgram", MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING);
// Create the variables x and y.
MPVariable x = solver.makeNumVar(0.0, 1.0, "x");
MPVariable y = solver.makeNumVar(0.0, 2.0, "y");
System.out.println("Number of variables = " + solver.numVariables());
// Create a linear constraint, 0 <= x + y <= 2.
MPConstraint ct = solver.makeConstraint(0.0, 2.0, "ct");
ct.setCoefficient(x, 1);
ct.setCoefficient(y, 1);
System.out.println("Number of constraints = " + solver.numConstraints());
// Create the objective function, 3 * x + y.
MPObjective objective = solver.objective();
objective.setCoefficient(x, 3);
objective.setCoefficient(y, 1);
objective.setMaximization();
solver.solve();
System.out.println("Solution:");
System.out.println("Objective value = " + objective.value());
System.out.println("x = " + x.solutionValue());
System.out.println("y = " + y.solutionValue());
}
}
In my case solution was simple - I just needed to add this singe line of code:
Loader.loadNativeLibraries();
where loader comes from com.google.ortools.Loader
Disclaimer: more a long comment than an answer...
note: I supposed you are using the github repository of or-tools if you used the binary package it should be more or less the same...
1) You must load the jni library which will load the OR-Tools C++ libraries and its dependencies...
/** Simple linear programming example.*/
public class Main {
static {
System.loadLibrary("jniortools");
}
public static void main(String[] args) throws Exception {
2) Did you manage to run the java samples ?
make run SOURCE=ortools/linear_solver/samples/SimpleLpProgram.java
ref: https://developers.google.com/optimization/introduction/java#simple_example
3) As Kayaman pointed out, you must pass the folder where the java runtime can find the native libraries (i.e. the JNI wrapper jniortools.dll and its dependencies libortools.dll)
if you look at the console log you'll see the full command line:
java -Xss2048k -Djava.library.path=lib -cp lib\sample.jar;lib\com.google.ortools.jar;lib\protobuf.jar ...\sample
Which comes from, the makefiles/Makefile.java file:
JAVAFLAGS = -Djava.library.path=$(LIB_DIR)
...
ifeq ($(SOURCE_SUFFIX),.java) # Those rules will be used if SOURCE contain a .java file
$(CLASS_DIR)/$(SOURCE_NAME): $(SOURCE) $(JAVA_OR_TOOLS_LIBS) | $(CLASS_DIR)
-$(DELREC) $(CLASS_DIR)$S$(SOURCE_NAME)
-$(MKDIR_P) $(CLASS_DIR)$S$(SOURCE_NAME)
"$(JAVAC_BIN)" -d $(CLASS_DIR)$S$(SOURCE_NAME) \
-cp $(LIB_DIR)$Scom.google.ortools.jar$(CPSEP)$(LIB_DIR)$Sprotobuf.jar \
$(SOURCE_PATH)
...
.PHONY: run # Run a Java program.
run: build
"$(JAVA_BIN)" -Xss2048k $(JAVAFLAGS) \
-cp $(LIB_DIR)$S$(SOURCE_NAME)$J$(CPSEP)$(LIB_DIR)$Scom.google.ortools.jar$(CPSEP)$(LIB_DIR)$Sprotobuf.jar \
$(SOURCE_NAME) $(ARGS)
endif
src: https://github.com/google/or-tools/blob/46173008fdb15dae1dca0e8fa42a21ed6190b6e4/makefiles/Makefile.java.mk#L15
and
https://github.com/google/or-tools/blob/46173008fdb15dae1dca0e8fa42a21ed6190b6e4/makefiles/Makefile.java.mk#L328-L333
note: you can run make detect_java to know the flags i.e. value of LIB_DIR
note: if you did use the precompiled package the Makefile is here:
https://github.com/google/or-tools/blob/stable/tools/Makefile.cc.java.dotnet
Then after you can try to add this option in Intellij...
You must understand that or-tools is a set of C++ native libraries which are wrapped to Java using the SWIG generator.
To make it work using Intellij (over a windows machine) you need to:
Install Microsoft Visual C++ Redistributable for Visual Studio
Download and extract the OR-Tools library for Java
In intellij, add jar dependency to the 2 jars under the lib folder of the extracted files (each of the 2 jars separately, do not add to lib folder itself. This is why).
Add the lib library path to VM options. In Intellij edit your run-configuration and add to vm options: -Djava.library.path=<path to the lib folder that hold the jars>
Load the jni library statically by adding the below code to your class (as mentioned here.)
static {
System.loadLibrary("jniortools");
}
I am trying to run some code found at https://darrenjw.wordpress.com/2011/01/01/calling-java-code-from-r/. It mentions that "It relies on Parallel COLT, which must be installed and in the Java CLASSPATH". This is what I am struggling to do.
This is what I have done (I've included my full paths / directory structure in case the points to some error)
I downloaded ParallelCOLT and saved in the directory
C:/Users/david/Documents/RWorkingDir/javaJAR/ParallelColt
I saved the code from the section "Stand-alone Java code" in the directory (also given below)
C:/Users/david/Documents/RWorkingDir/Gibbs/Gibbs.java
Taking a hint from How to include jar files with java file and compile in command prompt, I have tried to set the path to ParallelColt using
javac -classpath ".;C:/Users/david/Documents/RWorkingDir/javaJAR/ParallelColt/parallelcolt-0.9.4.jar;"
C:/Users/david/Documents/RWorkingDir/Gibbs/Gibbs.java # split for presentation
This executes without (visible) error and produced the Gibbs.class file in the Gibbs directory.
I have been unable to run this without error:
C:\>java C:/Users/david/Documents/RWorkingDir/Gibbs/Gibbs 10 1000 1
Error: Could not find or load main class:.Users.david.Documents.RWorkingDir.Gibbs.Gibbs
Caused by: java.lang.ClassNotFoundException:C:.Users.david.Documents.RWorkingDir.Gibbs.Gibbs
and trying to run from the actual directory
C:\>cd C:/Users/david/Documents/RWorkingDir/Gibbs/
C:\Users\david\Documents\RWorkingDir\Gibbs>java Gibbs 10 1000 1
Error: Unable to initialize main class Gibbs
Caused by: java.lang.NoClassDefFoundError: cern/jet/random/tdouble/engine/DoubleRandomEngine
I have had a read of What does "Could not find or load main class" mean? but have not found the error. Where are my errors please?
code from webpage:
import java.util.*;
import cern.jet.random.tdouble.*;
import cern.jet.random.tdouble.engine.*;
class Gibbs {
public static void main(String[] arg) {
if (arg.length != 3) {
System.err.println("Usage: java Gibbs <Iters> <Thin> <Seed>");
System.exit(1);
}
int N = Integer.parseInt(arg[0]);
int thin = Integer.parseInt(arg[1]);
int seed = Integer.parseInt(arg[2]);
DoubleRandomEngine rngEngine=new DoubleMersenneTwister(seed);
Normal rngN=new Normal(0.0,1.0,rngEngine);
Gamma rngG=new Gamma(1.0,1.0,rngEngine);
double x=0,y=0;
System.out.println("Iter x y");
for (int i=0;i<N;i++) {
for (int j=0;j<thin;j++) {
x=rngG.nextDouble(3.0,y*y+4);
y=rngN.nextDouble(1.0/(x+1),1.0/Math.sqrt(x+1));
}
System.out.println(i+" "+x+" "+y);
}
}
}
It can be compiled and run stand-alone from an OS shell with the following commands:
javac Gibbs.java
java Gibbs 10 1000 1
You need to run the java command from the directory that contains .class and supply the same -classpath as during compilation with javac.
cd C:/Users/david/Documents/RWorkingDir/Gibbs/
java -classpath ".;C:/Users/david/Documents/RWorkingDir/javaJAR/ParallelColt/parallelcolt-0.9.4.jar;" Gibbs 10 1000 1
If you find this tedious consider building an executable JAR.
I have a doubt about -cp and when should I use it. This is my scenario:
I have two .java, the first one:
package autos.tests.paquete;
public class MainAutos {
public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
Respotar objeto1 = new Respotar (x);
int mostrar = objeto1.repostar();
System.out.println(mostrar);
}
}
And the second one:
package autos.tests.paquete;
public class Respotar {
int gasolina;
public Respotar (int gasolina) {
this.gasolina=gasolina;
}
public int repostar (){
int gasolina = this.gasolina +20;
return gasolina;
}
}
Well, I am at root directory, and there, I have that directory: autos/tests/paquete
with both .java.
So I compile:
javac autos/tests/paquete/*.java
And execute from root directory:
java autos.tests.paquete.MainAutos 10
And it works, now here go my doubts:
1) I execute with java -cp . autos.tests.paquete.Main autos 10 and the behaviour is the same.
2) I move the Respotar.class from auto/tests/paquete to another directory, I compile with
java autos.tests.paquete.MainAutos 10 and it works.
3) I move the MainAutos.class from auto/tests/paquete to another directory, I compile with
java autos.tests.paquete.MainAutos 10 and it says: Error: Could not find or load main class autos.tests.paquete.MainAutos
4) I compile with java -cp . autos.tests.paquete.MainAutos (I have the .class on the current directory I am compiling, so I think I have to use -cp .) and it says the same:
Error: Could not find or load main class autos.tests.paquete.MainAutos
Thank you in advance, I hope someone can enlighten me, regards
java -cp is used to set any libraries such as jar file to your current classpath.
For the examples you have shown, you can do it in the below simple way
From you root directory compile your java files using the below command
javac -d . *.java
This would created those appropriate packages and place the class files under them
Then run you code using the command like this from the same root location
java autos.tests.paquete.MainAutos
I have looked at all the other stuff, mine is a compatibility issue I think, or PATH maybe. I have a bunch of classes I've been using since about 2008 and now the java command and the javac command can't find the classes even though they are in the same directory/folder. I have C:\Program Files\Java\jdk1.6.0_25\bin in the Path variable, but nothing in the Classpath. I normally have the compiled classes in the same folder with the java I'm compiling. I've been doing the same thing for 5 years! I have recompiled the lowest level class which is called WotifCat01. The compiler comes back with
WotifCat00.java:27:cannot find symbol
Symbol : WotifCat01
import java.io.*;
/** Find/replace program **/
class WotifCat00
{
private static int cnt;
private static String[][] filnamStrg={ {"Data/reftfile.txt","Data/AccumData/allreftfile.txt","","",""},
{"Data/reft1file.txt","Data/AccumData/allreft1file.txt","","",""},
{"Data/reft2file.txt","Data/AccumData/allreft2file.txt","","",""},
{"Data/reft3file.txt","Data/AccumData/allreft3file.txt","","",""},
{"Data/reft4file.txt","Data/AccumData/allreft4file.txt","","",""},
{"Data/work1file.txt","Data/AccumData/alltextsrc.txt","","",""},
{"","","","",""} };
private static String[] args1={"","","","",""};
public static void main(String[] args) {
while (filnamStrg[cnt][0] != "") {
args1[0] = filnamStrg[cnt][0];
args1[1] = filnamStrg[cnt][1];
WotifCat01 wotifCat01 = new WotifCat01();
wotifCat01.main(args1);
cnt++;
}
}
}
I've used this setup for a while and it worked fine on my laptop till now with Windows 7. I suspect something I've installed has overwritten something. This has to be really simple but I can't see it. I've removed jdk1.7.0_25 back to 1.6 but no change.
I backed up the classpath and deleted it. Now works fine. It contained IBM DB2 paths. DB2 I had installed in 2011 so discounted it, but it did have java paths in it so it must have overrode the path. I am not sure how DB2 managed to do so 2 years after install, I may have inadvertently activated something. Thanks for your input.
Neil Mc
I have written a code in java. In which I have created a package called xml-creator.
Package xml_creator has 3 classes say XML_Control, XML_Creator, and XML_implement.
When I run my project on netbeans (NetBeans 7.0) it works fine. But if I try to compile code on console, I get various errors like
When I compiled XML_Creator.java, I get following errors.
XML_Creator.java:371: cannot find symbol
symbol : variable XML_implement
location: class xml_creator.XML_Creator
typeAttr.setValue(XML_implement.table_col[i][2]);
^
XML_Creator.java:375: cannot find symbol
symbol : variable XML_implement
location: class xml_creator.XML_Creator
for(int j=0;j<XML_implement.kTab;j++)
^
XML_Creator and XML_implemenr both are in same package but non of them extend each other.
I am sorry I cant show code on this site as it is too large and aginst the company's policies.
I dont understand why it is showing me errors?
Sample code
XML_Control.java
package xml_creator;
public class XML_Control
{
public static void main(String as[])
{
XML_Creator xml = new XML_Creator();
}
}
XML_Creator.java
package xml-creator;
public class XML_Creator
{
XML_implement ixml = new XML_implement();
public XML_Creator()
{
System.out.println(""+ixml.a);
}
}
XML_implement.java
package xml_creator;
public class XML_implement
{
public int a;
public XML_implement()
{
a = 10;
}
}
So when I compile XML_Creator.java, console gives error.
It sounds like you're compiling within the directory containing the .java file, and only telling the compiler about one of the source files. That's the problem - to try to find a source or class file, the compiler is using the package name, and expecting the packages to be laid out in the conventional fashion. Compile from the root of the source tree - which I certainly hope you're using - like this:
javac xml_creator/*.java
You may also want to specify an output directory - which again will be the root of the directory hierarchy for packages:
javac -d bin xml_creator/*.java
If you're building regularly from the command-line (and not just for throwaway code) you should look into using a build system such as Ant.