How to run java class with custom variables from terminal - java

My scenario:
I have a Main.java file that simply does System.out.println("Hello").
I run it by first, compiling with javac Main.java and then excecuting the command java Main.
Now what I want is that instead of printing "Hello", it will print whatever the user wants, but I don't want to change the source code whenever I want a different output. So I replaced the System.out.println("Hello") with System.out.println(${MESSAGE}). But this gives error "Cannot resolve symbol MESSAGE".
Ultimately, I want a Main.class file and run with something like java Main -env MESSAGE=whateverIPutHere and it should print out whateverIPutHere.
Is it possible?

You can use system properties
public final class Test {
public static void main(String[] args) {
System.out.println(System.getProperty("port") + " port");
}
}
And then compile and run
javac Test.java
java -Dport=8080 Test
Output is : 8080 port

Now what I want is that instead of printing "Hello", it will print whatever the user wants, but I don't want to change the source code.
Simply not possible without changing code.
System.out.println("Hello")
Prints that string. End of story. And:
System.out.println(${MESSAGE})
is simply not valid Java. If you want to read an environment variable, see here how to do that.
But then: that is really a detour here. You can simply pass arguments on the command line:
java Main "some string" "and another one"
and then retrieve those two strings via the String args[] parameter that your main method receives!
The real answer here: you learn a new language by researching how that language works. You don't assume how syntax might look like, based on experiences from other languages. Meaning: $ENV_VAR is a "shell language" concept. Your idea: "maybe Java has the same" is a very inefficient strategy to go about this.

You can use the input arguments:
public static void main(String[] args) {
System.out.println(args[0]);
}
And then call it like this: java Main whateverIPutHere
Simple as that! args is an array containing all the arguments that you pass in the command line.

In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop. The arguments passed in command line is captured by args argument.
class test{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac test.java
run by > java test sonoo jaiswal 1 3 abc
Output:
sonoo
jaiswal
1
3
abc

You can either read it from args as mentioned above, or, if you know how to add a library to your project, try args4j. You'll get way cleaner code as you can use it to separate commandline argument processing to a dedicated class.

Related

IntelliJ and getting user input

so I'm new to using IntelliJ and I've tried googling but to no avail.
I'm creating a simple java program that basically prints hello and gets the user input (name) and prints it... Just to get the ball rolling. Normal Hello World prints fine..
But as soon as I add any [args] in it just crashes? Is there a way I can type the input in?
public class Main {
public static void main(String[] args) {
System.out.println("Hello, " + args[0] + "!");
}
}
You need to provide at least 1 argument if you access args[0] otherwise you get ArrayIndexOutOfBoundsException.
Why ? because the args[] is empty without any arguments passed so accessing the first one will throw the exception
How do you input commandline argument in IntelliJ IDEA?
There's an "edit configurations" item on the Run menu. In that panel, you can create a configuration and then you can choose the Class containing main().
add VM parameters and command-line args, specify the working directory and any environment variables.
you are done.
Sorry guys figured it out:
Go to Run
Edit Configurations > on the left side make sure you're in your Main class or whatever class you're using
Enter what you want in the program arguments. i.e. "James"

Using the java System.getProperty("Import")

I was doing some work for college and my main runs this:
Spreadsheet sheet = new Spreadsheet(0,0);
SpreadsheetManager manager = new SpreadsheetManager(sheet);
/* Read an Import file, if any */
String filename = System.getProperty("import");
if (filename != null)
sheet.parseInputFile(filename, sheet);
Thing is, when I actually try to import a file it doesn't do what is supposed to and the filename is always null, so it never reaches my parseInputFile.
My teachers made a bunch of code for different programming exercises that do similar things available, and I've also looked at projects my colleagues did in previous years, but every single one does what I am doing above.
I have to run my program like this: java -Dimport=A-002-002-M-ok.import calc.textui.Calc otherwise none of the tests given by the teachers will run.
I'm sorry if this is not a useful question, but I've tried looking everywhere. If anyone could explain how the System.getProperty("import") works and why it isn't working in this case, I would be very grateful.
I suggest you take a look at the documentation of System.getProperty().
Basically it retrieves a value from the system, either already present or set by you.
To avoid retrieving null you can use another method signature that specify a default value:
System.getProperty("import", "file.txt");
To set a System property, you can specify it at launch:
java -Dimport="file.txt" your_application
or set it programatically :
System.setProperty("import", "file.txt");
When you run your program with:
java -Dimport=foo
then the method call
System.getProperty("import")
should return "foo".
Is ist possible that you write a tiny example program to convince yourself? Without any SheetManagers and all stuff, just
class ItWorks {
public static void main(String[] args) {
System.out.println(System.getProperty("import"));
}
}
Call it thus
java -Dimport=indeed ItWorks
and report what happens.
That being said: if you want to pass command line arguments, why don't you use the facility for command line arguments? (i.e. the String[] array passed to main?)
You could then call your program like this:
java calc.textui.Calc my-nice-spreadsheet.data
=====================================================
Please write the follwoing in your calc.textui.Calc program immediately after the open brace of your class definition:
public class Calc ..... { // a line like this already exists
// insert next line here
public static String filename = System.getProperty("import");
// rest of your class, as before.
}
Then comment out the getProperty() line in your method that didn't work, but leave the rest including the System.out.println(filename);
Does it change?
Maybe system properties are not the most indicated way to do that (depends on your application).
You could also use command line arguments to pass the file name to your main method:
public class CommandLineExample {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("usage: CommandLineExample <filename>");
System.exit(1);
}
String filename = args[0];
if (filename !=null && !filename.isEmpty()) {
...
}
}
}
Your program should be called as:
java CommandLineExample theFileName
the string "theFileName" will be passed to the main method in args[0] (any additional words will be passed in subsequent positions of args {args[1], args[2], ...})
EDIT
if the program must be called with
java -Dimport=filename ...
then System.getProperty("import") will return the filename.
Confirm that you are calling the correct program (class name, package, version, last compile was successful, ...) and also check that the property is not mistyped like java -Dinport=A-... or has additional spaces, uppercase letters...

Send output to program arguments in Java eclipse automatically

In my ANJI (http://anji.sourceforge.net/) java project, I have two java file in package com.anji.neat.
One file names evolver.java which needs one program argument. The output champ-id from evolver.java is to be added as args[1] along with the previous argument fed to evolver.java
How can I add this output to Program Arguments without manually adding it? Plus is it possible that I execute these two java files in one run?
I know the question is complex, but someone kindlu help. I am new to java, so do not get things.
I would suggest that you have main method only in one file, lets say in evolver.java. Add a normal method in your second file which takes two arguments, first argument is the command line argument received in evlover.java and second argument is the champ-id. Run your program by calling the main method of evolver.java. Process the command line argument and generate the champ-id. And after that call the method of your second class by passing both the arguments.
It would become something "ugly" like:
public static void main(String[] args) {
if (args.length == 1) {
String extraArg;
...;
args = new Strinng[] { args[0], nextArg };
// main(args); return;
}
...
}

How to call a user defined Matlab from Java using matlabcontrol.jar

I am trying to call a user defined Matlab Function(M file) which takes 3 arguments(Java Strings) from my Java application which is developed in Eclipse. At the moment I am able to call proxy.eval and proxy.feval methods with the functions/commands like disp or sqr. But when i try to invoke a user-defined function it says on the matlab console that there is no such function defined like that and on the Java console MatlabInvocationException occurs.
Then I tried with a simple user-defined function which takes no arguments and just has single line disp('Hello') but still the result is same. So I think rather than a type conversion problem there is something wrong with how user-defined functions are getting invoked.
Please can anyone help me soon? I am meeting the deadline very soon for this project. I would be so thankful if someone can come up with a solution. (Mr Joshuwa Kaplan, is there any guide on solving an issue like this in your posts? I tried but found nothing)
Thanks in advance
You must have any user-defined m-files on the MATLAB search path, just as if you were working normally inside MATLAB.
I tested with the following example:
C:\some\path\myfunc.m
function myfunc()
disp('hello from MYFUNC')
end
HelloWorld.java
import matlabcontrol.*;
public class HelloWorld
{
public static void main(String[] args)
throws MatlabConnectionException, MatlabInvocationException
{
// create proxy
MatlabProxyFactoryOptions options =
new MatlabProxyFactoryOptions.Builder()
.setUsePreviouslyControlledSession(true)
.build();
MatlabProxyFactory factory = new MatlabProxyFactory(options);
MatlabProxy proxy = factory.getProxy();
// call builtin function
proxy.eval("disp('hello world')");
// call user-defined function (must be on the path)
proxy.eval("addpath('C:\\some\\path')");
proxy.feval("myfunc");
proxy.eval("rmpath('C:\\some\\path')");
// close connection
proxy.disconnect();
}
}
We compile and run the Java program:
javac -cp matlabcontrol-4.0.0.jar HelloWorld.java
java -cp ".;matlabcontrol-4.0.0.jar" HelloWorld
a MATLAB session will open up, and display the output:
hello world
hello from MYFUNC
You could also add your folder to the path once, then persist it using SAVEPATH. That way you won't have to do it each time.

how to pass java output as a matlab variable?

I have written a Java program which is invoked using system() function, thus it runs on the command window of Matlab. Now I want to know if there's another way to run a Java program other than running it on command window? Can it be run on any user made GUI in Matlab? Another problem is, I want to know if my program has some string value as output, which is generally displayed on command window, how can i store it in variable in Matlab?
Hope to hear from you very soon.
The Hello World solution by The MathWorks provides some insights on how to run a simple 'Hello World' java application inside MATLAB. You may change the Java code a bit, in order to have a method that returns a String.
public class HelloWorld
{
public String hello()
{
String helloWorld = "Hello World!";
return helloWorld;
}
}
Once this simple class is compiled and on the MATLAB JVM classpath create an instance and invoke the method with the following two commands.
o = HelloWorld
output = o.hello;
The String returned by the HelloWorld instance is assigned to the MATLAB variable output.
There is no need for a system command with Java code in MATLAB. You have direct access to the JVM from inside MATLAB. For an application with a complex GUI, break out to Java.
Undocumented Java is a valuable source on MATLAB, Java and GUIs.
Yes the classpath set is correct.
I modified the code, using it without main..
class HelloWorld
{
public String Hello()
{
String helloWorld="Hello World!";
return helloWorld;
}
}
Now, as per guided i try to create instance obj in Matlab, with following command:
o = HelloWorld;
Here I get following err:
??? No constructor 'HelloWorld' with
matching signature found.
The next command indicated it this:
output = o.hello;
which wouldnt work unless instance is created.

Categories