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.
Related
I have a simple java class as shown below:
public class Add2Numbers
{
public static void main(String[] args)
{
int num1=2, num2=4, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
I compile the class and run in matlab using:
obj = Add2Numbers;
javaMethod('main', o,"");
and I get the output: Sum of these numbers: 6 which is, of course, correct.
Next I change the code in my text editor (e.g. set num1=4) compile, execute the clear statements below:
clear all
clear java
clear import
clear CLASSES
clear ALL
clear
then run again:
obj = Add2Numbers;
javaMethod('main', o,"");
But the calculation result remains the same as before. If I close and restart MATLAB the modified java class runs correctly. So how on earth do I clear a java class without having to close MATLAB and restart it?
set
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.
I'm coding a Library program for my classroom, but I ran into an error quite immediately after compiling. The challenge for this program is that I need to use 3 files, only one of which (libraryRunner) actually has a Main in it. I'm trying to get both of the other method files (libraryCard and libraryBooks respectively) to work together.
I used Booleans before, and switched to Ints to see if that would fix it, but i get the same error. What's weird is that the program seems to compile, but the program just exits after the previously mentioned error.
Library Runner :
import java.util.Scanner;
public class libraryRunner
{
public static void main (String args[])
{
libraryCard Joseph = new libraryCard();
Joseph.whichBook("Sing");
}
}
What i'm using in Library Card :
...
public static String whichBook(String c)
{
if(libraryBooks.c == 1)
{
return("Sorry, it's already been checked out.");
}
else
{
return("Here's your book, " + c + "!");
}
}
}
What i'm using in Library Books:
public class libraryBooks
{
private static int hasBeenCheckedOut;
public libraryBooks()
{
libraryBooks.Sing(0);
}
public static int Sing(int c)
{
hasBeenCheckedOut = c;
return(hasBeenCheckedOut);
}
...
From what even my teacher tells me, the program should in theory compile and run, telling the user that the book "Sing" is now theirs. But I only get this error :
----jGRASP exec: java libraryRunner
Exception in thread "main" java.lang.NoSuchMethodError: libraryCard.whichBook(Ljava/lang/String;)Ljava/lang/String;
at libraryRunner.main(libraryRunner.java:8)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
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
I am somewhat new to JAVA. I've been working with it in college, but I have to admit, my instructor is of absolutely no help. She hardly knows JAVA herself, but that is another issue all in itself. I've been confused as to how methods and classes work. I'm creating this program that uses two files, one "main" file, and a "test" file. I can't seem to get the "main" file correct, as the compiler keeps telling me that it cannot find the symbols, even though they are. In the "test" file, I can't seem to get the compiler to recognize the methods from the "main" file. I have made sure that the files are in the same folder. I want to combine them into one file for simplicity, but I will lose points. I've included my code so far. I'm not looking for a "fix-it" solution, I just want to figure out why it's not working. ANY help is appreciated, since my instructor isn't of much assistance Thank you kindly!
MAIN FILE:
import java.util.Scanner;
class Fruit1 {
static Scanner console = new Scanner(System.in);
public static void main(String args[]) {
String color;
String taste;
}
public Fruit1() {
// generic constructor
color = "red";
taste = "yum";
}
public Fruit1(String aColor, String aTaste) {
// constructor with parameters
color = aColor;
taste = aTaste;
}
public Fruit1(String bColor, String bTaste) {
color = bColor;
taste = bTaste;
}
String getTaste() {
return taste;
}
String getColor() {
// Accessor method
return color;
}
}
TEST FILE:
import java.util.*;
public class Fruit1Test {
static Scanner console = new Scanner(System.in);
public static void main(String args[]){
Fruit1 a = new Fruit1("pinkish-red", "sweet-tart");
Fruit1 l = new Fruit1("yellow", "tart/sour");
a.taste();
a.color();
l.taste();
l.color();
System.out.println("Your apple is " + a.color + "in color and has a " + a.taste + " taste. ");
System.out.println("Your lemon is " + l.color + "in color and has a " + l.taste + " taste. ");
System.out.println();
}
}
a.taste(); will try to find method taste(); in your main file i.e. in Fruit1.java file. However as same is not found, it will throw error at compile time only that Method taste() is not found...
All below 4 statements will FAIL as those are not present...
a.taste();
a.color();
l.taste();
l.color();
As you are creating object of class by using below statement, already values to taste and color by use of constructor public Fruit1(String aColor, String aTaste){.
Fruit1 a = new Fruit1("pinkish-red", "sweet-tart");
I believe you now want to print the values of color and taste. To print those use getter methods that you have (getColor() & getTaste())
System.out.println("Your apple is " + a.getColor() + " in color and has a " + a.getTaste() + " taste. ");
System.out.println("Your Lemon is " + l.getColor() + " in color and has a " + l.getTaste() + " taste. ");
Note
You don't need to write public Fruit1(String bColor, String bTaste){ again as you have already defined above that....
Also your below statement should be before constructor and out of psvm
String color;
String taste;
Let me know if you are unclear...
Good Luck
You never declare the fields color or taste for the object Fruit1. Instead, you created the variables in the main method.
I suggest you read some basic tutorials on Java to get the hang of things. (Oracle also provides more advanced tutorials.)
I noticed in Fruit1, you are declaring the member variables in function main(). From the looks of it, Fruit1Test should have a main() fxn but Fruit1 should not. Take out those member variables out of main() and get rid of main() in Fruit1 (put it under the 'console' variable).
I also noticed that you have 2 constructors that both take in Strings. The compiler will probably complain about that too. I don't have a compiler in front of me but that's what I can tell just from looking.
For your first problem, it seems you're misunderstanding how to declare instance fields. You're creating them inside the main function, when you should create them directly inside the class.
For your second problem, see Fahim Parkar's comment, if it applies to your case. BTW it's a good practice to always have only one class/interface/enum per file, and have the file with the same name of the class (this second part may be mandatory in Java, I don't remember for sure - it applies to public classes, but I dunno if it also applies for "default, package protected" ones).
If they're named correctly, OTOH, maybe the error is because your "main" file didn't compile, so the "test" one didn't find it...
P.S. I just noticed you have two constructors with the same signature (number of parameters and same parameter types). You must remove one.