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.
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");
}
On Arch Linux, after upgrading to Gnome 3.14, I have several troubles with Webkit2Gtk.
Vala:
Consider the following vala test:
using Gtk;
using WebKit;
public class ValaWebkit : Window {
private WebView web_view;
public ValaWebkit(){
this.title = "Testing youtube";
set_default_size (800, 600);
web_view = new WebView();
add(web_view);
//this.web_view.open ("http://www.youtube.com/");
this.web_view.load_uri ("https://www.youtube.com/");
}
public static int main (string[] args) {
Gtk.init (ref args);
new ValaWebkit().show_all();
Gtk.main();
return 0;
}
}
Before upgrading to Gnome 3.14, I could copile like this valac --pkg gtk+-3.0 --pkg webkit2gtk-3.0 --vapidir . valawebkit.vala (I'm not pasting here webkit2gtk-3.0.vapi because it's too long). Now with gnome 3.14 if I try to compile i get
/home/luca/Sources/vala/webkit test/valawebkit.vala.c:8:29: fatal error: webkit2/webkit2.h: No such file or directory
#include <webkit2/webkit2.h>
^
compilation terminated.
error: cc exited with status 256
Compilation failed: 1 error(s), 0 warning(s)
Also, If I try to run the binary that I had compiled BEFORE upgrading to Gnome 3.14, I get this error:
./valawebkit: error while loading shared libraries: libwebkit2gtk-3.0.so.25: cannot open shared object file: No such file or directory
2) GJS / Eclipse / Java (SWT):
If I run either this gjs example, or eclipse (luna) or any other swt 4.4 based app, I get the following:
No bp log location saved, using default.
[000:000] Cpu: 6.58.9, x4, 2600Mhz, 7847MB
[000:000] Computer model: Not available
[000:000] Browser XEmbed support present: 1
[000:000] Browser toolkit is Gtk2.
[000:004] Using Gtk2 toolkit
[000:004] Warning(optionsfile.cc:47): Load: Could not open file, err=2
[000:004] No bp log location saved, using default.
I have the feeling that it is a kind of packaging issue on ArchLinux and Gnome 3.14. Does anyone is having the same issue? Is there a workaround both to compile and run against webkit2gtk?
EDIT
I made a little progress: I discovered that headers files I need are now under /usr/include/webkitgtk3.0 and /usr/include/libsoup-2.4. Now, compiling like this:
valac --pkg gtk+-3.0 --pkg webkit2gtk-3.0 --vapidir . --Xcc="-I/usr/include/webkitgtk-3.0" --Xcc "-I/usr/include/libsoup-2.4" --thread valawebkit.vala
works, but it sill fails on linker:
/tmp/ccQGhB3b.o: In function `vala_webkit_construct':
valawebkit.vala.c:(.text+0x6e): undefined reference to `webkit_web_view_new'
valawebkit.vala.c:(.text+0x101): undefined reference to `webkit_web_view_load_uri'
collect2: error: ld returned 1 exit status
error: cc exited with status 256
Compilation failed: 1 error(s), 0 warning(s)
There fact that you have to specify the --Xcc flags suggests that you are missing the pkgconfig file for WebKit. There should be a webkit2gtk-3.0.pc in /usr/lib/pkgconfig. The Arch package webkit2gtk has a pkgconfig file named webkit2gtk-4.0.pc. So, if you rename your VAPI file, that should link properly.
Actually with webkit2gtk-4.0 I don't need to provide a vapi file any more. So I can delete my webkit2gtk-4.0.vapi and complile like this (even simpler):
valac --pkg gtk+-3.0 --pkg webkit2gtk-4.0 --thread valawebkit.vala
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
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am at a very introductory level of programming with java. I am writing a simple code that involves taking an investment and adding an intrest rate into it. The code is not finished yet but I hav run into the java.lang.ClassNotFoundException error. Since I am so new to java, I have not yet run into this problem before. Where my confusion comes in is the program will compile. I really don't know how to approach this problem.
As I said I dont have a clue about where to start on this, here is the error.
Exception in thread "main" java.lang.NoClassDefFoundError: CDCalc/java
Caused by: java.lang.ClassNotFoundException: CDCalc.java
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
The entire code
import java.util.Scanner;
public class CDCalc
{
public static void main(String args[])
{
int Count = 0;
int Investment = 0;
double Rate = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you want to invest?");
int Invest = userInput.nextInt();
System.out.println("How many years will your term be?");
double Term = userInput.nextInt();
System.out.println("Investing: " + Investment);
System.out.println(" Term: " + Term);
if (Term <= 1)
{
Rate = .3;
}
else if (Term <= 2)
{
Rate = .45;
}
else if (Term <= 3)
{
Rate = .95;
}
else if (Term <= 4)
{
Rate = 1.5;
}
else if (Term <= 5)
{
Rate = 1.8;
}
System.out.println("Total is: " + (Rate * Invest));
}
}
I would greatly appreciate any help on this. Thanks
edit
I apologize, I should have included this. The code did compile just fine, the problem came in when I ran it. I did use javav CDCalc.java and java CDCalc and thats when the error came up. The even stranger thing is I didn't change a thing, closed out terminal and my text editor, deleted the saved files, reopened everything, saved it, compiled it, and it runs fine now. I apologize again for this post but it seems it fixed itself! –
Your code should compile fine. The way you compile Java files is different than how you execute them.
You compile with
javac CDCalc.java
...and run them with
java CDCalc
Looks like you tried to run it as java CDCalc.java, but it should be just java CDCalc.
The Java command takes a class name (not a file name), so there is no ".java" at the end, and no slashes or backslashes but dots for the package name (your class does not have a package).
This is an sample example:
public class HelloWorldDemo {
public static void main(String args[]) {
System.out.println("Hello world test message");
}
}
This is sample hello world program,When i compile this program using javac HelloWorldDemo.java command, this compiles fine and generates HelloWorldDemo.class in the current directory,
After running this programm using java HelloWorldDemo command, I am getting the below exceptions.
Exception in thread "main" java.lang.NoClassFoundError: HelloWorldDemo
thread main throws this error and exit the program abnormally.
This reason for this error is java virtual machine can not find class file at run time. java command looks for the classes that are there in the current directory, so if your class file is not in current directory, you have to set in classpath, so the solution is to place this .class file in the classpath
classpath is the enviornment variable in every system which points to class files in the directories. if you classfile is in jar file, jar should be in classpath. classpath can be absolute(complete path) or relative path( related to directory )
solve java.lang.NoClassDefFoundError :-
HelloWorldDemo.class is not avialble at runtime, so we have to set the class file to java command using -classpath option
java -classpath . HelloWorld
This is for fixing NoClassDefFoundError error by setting classpath inline for java command.
We are instructing the jvm to look for the HelloWorldDemo.class in the current directory by specifying .
if class file is in different directory, we need specify the complete directory absolute or relative path instead of . for java command
Fix for java.lang.NoClassDefFoundError in windows:-
To solve NoClassDefFoundError error in windows , we have to set CLASSPATH environment variable.
to set classpath in windows, we have to configure the below values
set CLASSPATH=%CLASSPATH%;.;
%CLASSPATH% means existing classpath to be added and . points to current directory
After setting classpath,
java HelloWorldDemo
command works fine and prints hello world message
Your program seems fine. Did you compile your java file using Javac?
You need to perform steps below:
Compiling the .java file (source code) using javac
javac CDCalc.java
This should create a class file named CDCalc.class
Executing the compiled class file using java
java CDCalc
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