Use java in matlab - java

I encountered a problem when I tried to use java from matlab. I read through the tutorials from MathWork.com several times, also I re-installed the JDK1.6, in order to be compatible with matlab. However, after my work, it still doesn't work...
Here is the contents in classpath.txt:
C:\Program Files\MATLAB\R2010a\java\jarext\xstream.jar
C:\Program Files\MATLAB\R2010a\toolbox\javabuilder\jar\win64 \javabuilder.jar
DYNAMIC JAVA PATH
C:\Users\Gao\Desktop\connected_components_labeling
Clearly, the directory is included in the file.
The connected_component_labeling is just a folder on my disk. The classes that I want to use in the connected_components_labeling are: Disjoint_Set.class and Node.class are in the connected_components_labeling folder.
I tried:
x = Disjoint_Set();
also
x = connected_components_labeling.Disjoint_Set();
None of them work. The only feedback I got from matlab is:
??? Undefined variable "connected_components_labeling" or class
"connected_components_labeling.Disjoint_Set".
I'm pretty frustrated. Could anyone help me out? I'd appreciate it. Thanks a ton!

Make sure that you are compiling the java files using a JRE/JDK that MATLAB is compatible with. As far as I can tell, MATLAB does not work properly with Java 7, so stick with Java 6 for the moment...
There are a couple of environment variables that affect MATLAB. In my case I have:
JAVA_HOME = C:\Program Files\Java\jdk1.6.0_32
MATLAB_JAVA = C:\Program Files\Java\jre6
PATH = ...;C:\Program Files\Java\jdk1.6.0_32\bin
Here is a simple test I just did:
C:\work\Student.java
public class Student {
private String name;
public Student(String str) {
name = str;
}
public void setName(String str) {
name = str;
}
public String getName() {
return name;
}
public static void main(String args[]) {
Student s = new Student("amro");
s.setName("unknown");
System.out.println("Hello " + s.getName());
}
}
I compile: javac Student.java (the output is placed in the same directory c:\work\Student.class). Now I test it from MATLAB:
javaaddpath('C:\work')
javaMethod('main','Student','')
s = Student('me')
char( s.getName() )
I get:
Hello unknown
s =
Student#8d6877
ans =
me

Related

Can't find main(String[]) method in class: TapeDeck. The main method is in the other class which runs the program

I have two classes. When the I put class TapeDeckTestDrive first on the text editor, it runs fine. When I put the TestDrive class first, it gives the error that it can't find the main class. Why is this?
class TapeDeck {
boolean canRecord = false;
void playTape(){
System.out.println("tape playing");
}
void recordTape(){
System.out.println("tape recording");
}
}
class TapeDeckcTestDrive{
public static void main(String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
ERROR ON THIS FORMAT
VS
FOLLOWING WORKS FINE:
class TapeDeckcTestDrive{
public static void main(String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
class TapeDeck {
boolean canRecord = false;
void playTape(){
System.out.println("tape playing");
}
void recordTape(){
System.out.println("tape recording");
}
}
After you compile the code using the command:
javac fileName.java
Run the java .class file by only specifying fileName without the .java extension
java fileName
if you use fileName.java it won't run the specific .class file; it will try to interpret the .java file. if you want to interpret a .java file then parent class must contain the main(String[]) method.
First, You have to compile the File by using javac.
Then, You have to Run the file.
Classname where main is written.
javac filename.java
java classname
You Can Run the java program in two ways.
Directly run the java program by
java example_program.java
In this type compilation and Execution happens at runtime. That is
Byte codes is generated and executed immediately(works as a interpreter)
So,You must use the superclass(Containing the main method) at first followed by other
compound classes.
Note:
No .class file will generate. That means, it will generate byte code internally and will execute. Programmer's cannot view the class file.
In Second type, First, you should compile,
javac example_program.java
It will generate the example_program.class . Then, Execute the class file using,
java example_program
Here, the order of writing classes doesn't impact. you can write the classes in any order. it will work fine.
I split it into two files and added public to the classes/methods as well as the boolean. Now the code runs.
In some JDK's , JVM looks after the entry point function first due to which it need to be written first then the rest of the code. As main function is our entry point function it must be written first.
Steps 1.
--You have to compile the File by using javac. Then, You have to Run the file.
--Classname where main is written.
-- javac filename.java
-- java classname
It causing error due to:-
class TapeDeck {
boolean canRecord = false;
void playTape(){
System.out.println("tape playing");
}
void recordTape(){
System.out.println("tape recording");
}
}
class TapeDeckcTestDrive{
public static void main(String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
--Your tapedeck class doesn't main (String[]).
I got your problem.
First of all, check your classpath that you have set in Environment Variables
Follow the following steps:
***Step 1: *** Right Click on This PC --> Advanced system settings --> Environment Variables
***Step 2: *** Edit the variable classpath and add a new path or edit your old path that you have set. The path should be: C:\Program Files\Java_Home\jdk..\lib;.;
Note: The "." is must after a semicolon (;).
***Step 3: *** Close the CMD and open it again.
***Step 4: *** Now compile your using javac command: javac FileName.java
***Step 5: *** Run your code using java command: java ClassName
And there you go...
Try to put "public static void main" class first and then other methods in your code. It will definitely work.

Java Path Finder NumericValueChecker

I am trying to learn Java Path Finder (JPF). I downloaded the JPF and build it. Currently I have jpf-core folder which has example .java files together with their corresponding .jpf files. My goal is to create a new basic .java file and check whether a specific value in this file exceeds the max-bound I specified in the .jpf file.
In the examples folder there is .java file called NumericValueCheck.java which is exactly what I want, and it works as expected. (finds when the value exceeds the bound)
NumericValueCheck.java
public class NumericValueCheck {
public static void main (String[] args){
double someVariable;
someVariable = 42;
someVariable = 60;
}
}
NumericValueCheck.jpf
target = NumericValueCheck
listener = .listener.NumericValueChecker
# NumericValueChecker configuration
range.vars = 1
range.1.var = NumericValueCheck.main(java.lang.String[]):someVariable
range.1.min = 0
range.1.max = 42
However, I created a new .java file and named it "BasicCheck.java". Here is the code inside it;
public class BasicCheck {
public static void main(String[] args){
double result;
result = 60;
result = 110;
}
}
Here are the properties in BasicCheck.jpf;
target = BasicCheck
listener = .listener.NumericValueChecker
# NumericValueChecker configuration
range.vars = 1
range.1.var = BasicCheck.main(java.lang.String[]):result
range.1.min = 0
range.1.max = 60
I compiled the BasicCheck.java using javac BasicCheck.java in a separate directory. Then I copy "BasicCheck.java" and "BasicCheck.jpf" to examples folder of jpf-core where NumericValueCheck.java and NumericValueCheck.jpf also in the same place. I also copy "BasicCheck.class" to jpf-core/build/examples directory where "NumericValueCheck.class" also in the same place.
However, when I run the command java -jar build/RunJPF.jar src/examples/BasicCheck.jpf, it can't find any error. The result is "no error detected". It should detect 110 which is bigger than the upper bound 60.
Why is it not working? Do I need to add something extra to my new BasicCheck.java or BasicCheck.jpf ?
Thanks in advance.
I found the solution after a long effort. The solution is simple.
Put BasicCheck.java and BasicCheck.jpf under the directory jpf-core/src/examples.
Do NOT compile to source using javac. Open the terminal and cd to jpf-core directory. Then type the following command: ./gradlew buildJars.
That's it. Now you can use the command java -jar build/RunJPF.jar src/examples/BasicCheck.jpf to run Java Path Finder.

JAVA Exception while using printf along with format specifier for int. Exception occurred in PrintStream as posted below [duplicate]

Why do I get the following compilation error with a simple call to printf? My code:
import java.util.Scanner;
public class TestCodeBankAccInputs
{
public static void main(String[] args)
{
String displayName = "Bank of America Checking";
int balance = 100;
System.out.printf("%s has %7.2f", displayName, balance);
}
}
On compilation I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method printf(String, Object[]) in the type PrintStream is not applicable for the
arguments (String, String, double)
at TestCodeBankAccInputs.main(TestCodeBankAccInputs.java:9)
What's causing this and how can I fix it?
Version information:
Help->About in Eclipse gives following information:
Eclipse Java EE IDE for Web Developers.
Version: Indigo Release
Build id: 20110615-0604
The JDK I installed is JDK1.6.0_27
I have seen this similar issue regarding String.format. Some users have suggested it might be a build issue, but looks like I have updated versions.
Check that the Compiler compliance level is set to at least 1.5 for your project:
Project > Properties > Java Compiler
if Enable project specific settings is not set, use the Configue Workspace Settings... link on that page to check the global Compiler compliance level.
It seems peculiar that this has popped up again (same issue as the other post you linked). I wonder if there's a bug in a recent version of Eclipse? The asker on that other post never came back with any more info, so I suspect that it might have just gone away. Your code works perfectly fine. If I supply an appropriate BankAccount class, it compiles and runs as expected both in IntelliJ 10.5.2 and from the command line with javac and java, version 1.6.0_26:
import java.util.Scanner;
public class TestCodeBankAccInputs {
public static void main(String[] args) {
Scanner inStream = new Scanner(System.in);
BankAccount myAccount = new BankAccount(100, "Bank of America Checking");
System.out.print("Enter a amount: ");
double newDeposit = inStream.nextDouble();
myAccount.deposit(newDeposit);
System.out.printf("%s has %9.2f", myAccount.displayName(), myAccount.getBalance());
//System.out.printf("%3s", "abc");
}
static class BankAccount {
private double balance;
private String name;
public BankAccount(double balance, String name) {
this.balance = balance;
this.name = name;
}
public String displayName() {
return name;
}
public double getBalance() {
return balance;
}
public void deposit(double newDeposit) {
this.balance += newDeposit;
}
}
}
I still (as I did for the other post) recommend a clean build, but have you checked your compiler compliance level in Eclipse? You can be compiling with a 1.6 JDK but still have a lower compliance level set in an IDE, which can make funny things happen.
A temporary fix like this might work.
Instead of using printf, use this:
System.out.printf("%s has %7.2f", new Object[]{
myAccount.displayName(), myAccount.getBalance()
} );
This might fix your problem.
Use: System.out.printf(arg0, arg1, arg2) instead of System.out.printf(arg0, arg1).

running .class files with java.exe - Error: Could not find or load main class

code:
package pack1;
public class Demo01 {
public void run() {
System.out.println("--running Demo01--");
demoMethod1();
}
private void demoMethod1() {
int foo = 5;
int bar = 10;
int res = foo+bar;
System.out.println("res: "+res);
}
public static void main(String[] args){
Demo01 demo01 = new Demo01();
demo01.run();
// new change...
Demo02 demo02 = new Demo02();
demo02.run();
}
}
rest can be found here: https://code.google.com/p/ci-research-teamcity-test-project/source/browse/#svn%2Ftrunk%2Fsrc%2Fpack1
I'm trying to run the .class files with java.exe through the command line to no avail.
Yes I've looked for solutions, tried running the root folder with the -cp flag but I keep getting the same error. Works just fine in Eclipse.
Ok, we have several points to note at this point.
The class is in a package. Thus, it must be in a folder names exactly as the package name ("pack1" in your case).
Your folder structure must be like this:
"root folder" (X)
| pack1
| Demo01.class
| Demo02.class (as I just noticed that you are also referring to it in the code)
Then, in order to start it, you have to be in the parent folder (this has to be the current working directory; marked with X) of "pack1" and execute
java pack.Demo01
Note, you have to use the whole canonical class name for referencing it, without .class at the end.
If you don't want or cant change the current working directory to the "root folder" you can use -cp PATH as first parameters to java.exe.

How do I call java code from a Matlab program

I would like to calling my own Java program from Matlab.
This is my java program:
public class TestArgu{
public static void main(String[] args){
System.out.println("Test passing arguments!");
}
public void addNumber(int aNumber){
ansNumber = aNumber+5;
chk = aNumber;
System.out.println("input number = " + chk + ".\n");
System.out.println("ans = " + ansNumber + ".\n");
}
public int ansChk(){
return ansNumber;
}
private int ansNumber;
private int chk;
}
I did step by step from this link
http://www.mathworks.nl/support/solutions/en/data/1-URS0E/?...1...
but it is not working with my program.
I'm running Matlab program from the Server computer.
So I cannot edit the classpath.txt.
How to fix this problem?
First, delete the main function from your class. Then add the line
package mypackage.release;
before your class definition. Then compile it using the command
javac -verbose -cp /home/javaclasses -d /home/javaclasses /home/javasource/TestArgu.java
In matlab type
javaaddpath('/home/javaclasses');
clear java;
import mypackage.release.*;
test=TestArgu;
test.addNumber(6);
test.ansChk();
Remember that everytime you make changes and compile the java class, you must call clear java in matlab before the changes are available. This also has the unfortunate side effect of clearing all the variables in your workspace so make sure you don't have anything important to save before calling it.

Categories