I've just started using eclipse and java and I'm not used to either one of them. I wrote a simple helloworld-programm, but the next task (school) was to create a program that takes a userinput (from commandline) and responds with the highest number of two. The code I wrote looks like following:
public class Larger {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if(args.length < 2)
{
System.out.print("Too few parameters submitted.");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.print(Math.max(num1, num2));
}
}
It all works well when I hit the "run"-button in eclipse, but later when I browse the source-files and tries to run "java Larger.class 2 4" i get an error from java.exe saying that no class was found.
Any idea what this can be?
When it fails, are you invoking the Java process through Eclipse or the command line? It sounds like you're doing it from the command line. In that case, you don't specify the ".class" portion when invoking your Java program. Try :
java Larger 2 4
The "run" button launch your program with the adequate classpath (the bin folder where the .class is generated)
alt text http://ftp.sumylug.osdn.org.ua/pub/mirrors/eclipse.org/downloads/drops/R-3.2-200606291905/new_noteworthy/images/rt-classpath.png
the java needs to refer to that same bin folder, and use the class name (not the class generated binary)
java -cp bin Larger 2 4
To compile javac Large.java
To run java Larger 2 4
Related
I have a java class, which has 3 methods and each method returns a String. I exported the .jar file out of that Java project. When I run the jar file from git bast using the command ./script1.sh, I get the output in the command window. My question is, how can I assign those values to the three variable that are in the script1.sh file. If I type echo ${"Source_branch"}, i should get output as "XXX_Source_Branch".
Here is my Java code :
package com.main;
public class Engine {
public static void main(String[] args) {
try {
getSourceBranch();
getDestinationBranch();
getDestEnv();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getSourceBranch() {
return "XXX_Source_Branch";
}
public static String getDestinationBranch() {
return "XXX_Dest_Branch";
}
public static String getDestEnv() {
return "XXX_Dest_Env";
}
}
The name of the jar file is Engine.jar.
And my script file is
runjar.sh
java -jar Engine.jar
Source_branch
Destination_brnach
Destination_env
pass data from java to bash
If you want to save data from java to the overlaying String, you will need to print that to System.out and read them from the shell.
Java code:
System.out.println("your source branch")
System.out.println("your destination branch")
Shell code
out="$(java -jar Engine.jar)"
sBranch="$(echo "$out"|sed -n '1p' /dev/stdin)"
destBranch="$(echo "$out"|sed -n '2p' /dev/stdin)"
pass data from bash to java
If you hard-code the Strings, java will just use the Strings. If you want to change that, you will need to modify your java code.
option 1 - arguments
If you want to pass the strings in the script using java -jar Engine.jar Source_branch Destination_brnach Destination_env, you can use them in your main method with the args parameter.
For example, you can print the first String in your main method using
System.out.println(args[0]);
If you do that, please test if args.length is greater than the highest argument you are accessing.
option 2 - System properties
If you want to get parameters without accessing args(independent of your main method), you will need to use System properties.
At first, change the script to be like that:
java -jar -DSource_branch=yourSourceBranch -DDestination_branch=yourDestinationBranch -DDestination_env=yourDestinationEnv
Engine.jar
Note that -D. That indicates that you are passing System properties. The syntax for this is -D<key>=<value> and it should be located between java and -jar.
Also, you will need to use System.getProperty() to access it from anywhere in your code.
For example:
public static String getSourceBranch() {
return System.getProperty("Source_Branch");
}
Create a .sh file with any file editor, like-
$> vi runJar.sh
Then, paste the below script ,
#!/bin/sh
java -jar Engine.jar
After saving the file, give execution permission -
$> chmod +x runJar.sh
Then run using
$> ./runJar.sh
Make sure the jar file and shell script file are in the same directory.
I want to use matlab function in java application. I create java package from my function by deploytool in matlab. Now, how can i use this package? Can only import the jar file created by deploytool in my java project and use its function?
After a lot of googling, I used this toturial but in the final step, i get error "could not load file".
Also i read about MatlabControl, but in this solution, we should have matlab environment in our system to java code running. But i will run my final app in systems that may not have matlab at all.
So i need a solution to run matlab function in java class even in absence of matlab environment.
Finally I solve my problem. the solution step by step is as follows:
write matlab function:
function y = makesqr(x)
y = magic(x);
Use deploytool in matlab and create java package.
3.create new java application in Eclipse and add main class. import javabuilde.jar and makesqr.jar:
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import makesqr.Class1;
and main.java:
public class main {
public static void main(String[] args) {
MWNumericArray n = null;
Object[] result = null;
Class1 theMagic = null;
try
{
n = new MWNumericArray(Double.valueOf(5),MWClassID.DOUBLE);
theMagic = new Class1();
result = theMagic.makesqr(1, n);
System.out.println(result[0]);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(n);
MWArray.disposeArray(result);
theMagic.dispose();
}
}
}
add javabuilder.jar and makesqr.jar to java build path of your project.
run it.
the Double.valueOf(3), define the input for our function and the output is as follows:
8 1 6
3 5 7
4 9 2
I didn't get properly your problem. Did you already compile the jar file from Matlab code and you are trying to use that, or you are at the last step of the tutorial?
If your answer is the latest case, most probably you forgot the "." before the class path.
From tutorial you linked:
You must be sure to place a dot (.) in the first position of the class path. If it not, you get a message stating that Java cannot load the class.
Also check if the matlab compiler path ("c:\Program Files\MATLAB\MATLAB Compiler Runtime\v82\toolbox\javabuilder\jar\javabuilder.jar" - in the tutorial) is correct for your system.
I wanted to find out how to create an executable .jar file, so I wrote a small sample program to test it. This sample program takes some default text and turns it into some code based on the Caesar code. Anyway, it outputs normally when run in Eclipse.
I doubt this helps, but here's the source code for the two java classes.
Main.java
public class Main {
public static void main (String [] args){
Caesar caesarCode = new Caesar();
caesarCode.setDecodedText("this");
caesarCode.setShiftPos(3);
String cipherText = caesarCode.deencode(caesarCode.getDecodedText(), caesarCode.getShiftPos());
System.out.print(cipherText+"\n");
String plainText = caesarCode.deencode(cipherText, caesarCode.getShiftPos()*-1);
System.out.print(plainText);
}
}
Caesar.java
public class Caesar {
// global variables
String encodedText; // encoded text
String decodedText; // decoded text
int shiftPos; // shift positions to decode message
// getters and setters
public String getEncodedText() {
return encodedText;
}
public void setEncodedText(String encodedText) {
this.encodedText = encodedText;
}
public String getDecodedText() {
return decodedText;
}
public void setDecodedText(String decodedText) {
this.decodedText = decodedText;
}
public int getShiftPos() {
return shiftPos;
}
public void setShiftPos(int shiftPos) {
this.shiftPos = shiftPos;
}
public String deencode (String plainTextArg, int shiftPosArg) {
// variables
String plainText = plainTextArg;
char[] cipherTextArray;
String cipherText;
int plainTextSize;
int shiftPos = shiftPosArg;
// initialize variables
char[] plainTextArray = plainText.toCharArray();
plainTextSize = plainTextArray.length;
cipherTextArray = new char[plainTextSize];
// shift cipher String by shiftPos
for (int i = 0; i < plainTextSize; i++){
cipherTextArray[i] = (char) (plainTextArray[i] + shiftPos);
}
cipherText = String.valueOf(cipherTextArray);
// return cipher text
return cipherText;
}
}
I created my .jar file this way (on a Mac):
Created two directories on Desktop: "classes" and "source"
Copied my two files (Caesar.java, Main.java) into the source folder.
I compiled the files into .class files in the classes directory with the command "javac -d ../classes *.java"
I created a manifest.txt file with the line "Main-Class: Main", and saved it as "manifest.txt" in the classes directory.
I then created the .jar file with this command "jar -cvmf manifest.txt main.jar *.class".
The main.jar file was created successfully.
The problem is, when I ran it, nothing happened - no warnings, no popups, no error messages.
I'm thinking that it has something to do with the fact that it outputs to the terminal, but I can't wrap my head around it. I've also looked at many threads on this forum and others, but can't seem to see the problem. I'm going to experiment to see if it works for a GUI application in the meanwhile.
Greatly appreciate your help on this, thanks!
I'm thinking that it has something to do with the fact that it outputs to the terminal
If you want to see console output from your program then you will have to run it in the Terminal with java -jar main.jar. If you double click the JAR in the Finder or use the open command then it will run but any output will go to the system console log rather than being displayed directly. You can show system console messages by running syslog -C.
In Windows, press Windows+R to invoke "Run..." dialog. Type cmd there and hit Enter. The Command Prompt window will appear (it's black).
At the prompt type cd %USERPROFILE%\Desktop\classes and hit Enter.
Then type command as suggested above: java -jar main.jar
It is possible to create executable jars from within eclipse if you want to.
Right click on your project -> Export -> Java -> Runnable JAR file.
Note that You might need to run your jar file from the command line using java -jar <jarFile> to see System.out.println() and error messages.
I am still a Java newbie and I have this code. I don't know how to pass the input file to the code. I am using Eclipse Juno.
public static void main(String[] args) {
In in = new In(args[0]); // input file
int N = in.readInt(); // N-by-N percolation system
// turn on animation mode
StdDraw.show(0);
// repeatedly read in sites to open and draw resulting system
Percolation perc = new Percolation(N);
draw(perc, N);
StdDraw.show(DELAY);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
perc.open(i, j);
draw(perc, N);
StdDraw.show(DELAY);
}
}
Whenever I run it I get this exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at PercolationVisualizer.main(PercolationVisualizer.java:42)
What might cause this exception? Could you please be patient with me and explain the process of how to call the input file in the code?
Refer to this guide for adding arguments to your program. Alternatively, you could specify the file name directly in the code instead of reading it from the args.
Basically, the guide instructs the user to go to the Run menu, then "Run..." (actually "Run Configurations..." in recent Eclipse versions), select the appropriate run configuration for the desired project, click the Arguments tab, and enter the arguments (such as file name) in the "Program arguments" section, separated by spaces.
For those using IntelliJ you can set the program arguments via Run->Edit Configuration. Look down about the middle of the window to locate the "Program Arguments" field. Then add the path to the test file and save.
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