Java: Making an Optional Command Line Argument - java

I am working on a program that is supposed to take one required command line argument and one optional command line argument. The first argument is the name of an output file where data will be written to, and the second is a number that will be used to calculate the data to be written to the output file. If the user does not enter a number, then it should just use a default value to calculate the data. For example, if the user entered command line arguments "Foo.csv 1024" the program would use 1024 to calculate the data and write it to Foo.csv, but if the user only used the command line argument "Foo.csv" then the program would use a default value of 2048 to calculate the data and write it to Foo.csv. I am creating/running this program using the Intellij IDE. How would I do this? Any advice/suggestions would be much appreciated.

Your program seems to be simple, so the solution is also simple for this particular case. You can test how many arguments were passed to the program checking the argument args of your main function:
public static void main(String[] args){...}
args is an array that contains the arguments passed to your program. So if your program is called prog and you run it with prog Foo.csv 1024, then args will have:
args[0] = "Foo.csv";
args[1] = "1024";
With this, you know which arguments were passed to your program and by doing args.length, you can know how many they were. For the example above, args.length=2 If the user didn't indicate the last argument ("1024"), then you would have args.length=1 with the following in args:
args[0] = "Foo.csv";
So your program would be something like:
public static void main(String[] args){
//The default value you want
int number = 2048
if(args.length==2){
number = Integer.parseInt(args[1]);
}
//'number' will have the number the user specified or the default value (2048) if the user didn't specify a number
}
To supply arguments to your program you must run it on a console or some kind of terminal. Using IntelliJ (or any other IDE) it's also possible to run the program with arguments, but you specify those in the Run Settings.
If you want a more complex treatment of arguments, usually what you want is done by argument parsers. These are usually libraries that take you argv and help you reading arguments to your program. Among other things, these libraries usually support optional arguments, arguments supplied via flags, type checking of arguments, creating automatic help pages for your commands etc. Consider using an argument parser if your argument requirements are more complex or if you just want to give a professional touch to your program :)
For java i found this particular library: http://www.martiansoftware.com/jsap/doc/

Related

Java - Possible main method arguments in windows

I wondered whether there was any connection between the main method's parameter String[] args and the possibility of opening files with a specified program.
Considering that I wrote a simple program that writes down every String of args, then opened some files with this program (I am using windows).
This is what happened:
No matter what kind of file I opened with my program (right click -> open with...), argscontained only one String which was the file's complete path.
When I ran the program on itself, args was of length 0.
Now my question is: are there any other Strings that might be contained in args or would the following code always work without doubt?
(I want to use this on windows, not play around with it like java MyProgram 1 2 3 "test"
public static void main(String[] args) {
initProgram();
if (args.length != 0) { //file opened with program
loadFile(new File(args[0]));
}
}
Thank you for your answers and please be patient with my english.
Just like Marcos Vasconcelos assumed: by opening multiple files at once args will contain all the files' paths tried to open, so args can be larger than just one String. Its length depends on the amount of files that want to be opened with the program.

How can a script take different types of command line arguments and feed it to a java program?

So I need to make a java program that represents a bank tiller. However, I need to use an executable script that will feed the command line arguments to the java program. Unfortunately, there are multiple types of commands I can do that would need to call the java program.
Since there are different types of command options (start, buy, and change, I do not know how I could go about feeding the right argument information to the java program. Any assistance would be greatly appreciated.
Unless I'm missing something, you could use $# to pass the script's arguments to your Java program. For example,
#!/usr/bin/env bash
export CLASSPATH="$HOME/src/java/"
java com.example.MyTeller "$#"
Pass the script arguments to your Java program:
java programName "$#"
Here is a sample:
public class PrintArgs {
public static void main (String[] args) {
for (int x=0; x<args.length; x++) {
System.out.println(arg[x]);
}
}
}
Call it like this:
java PrintArgs start 80 = 10 2 2 2
The script I am not that sure about, but I you can look it up. Google shell scripts arguments.
Take a look at the Apache CLI stuff. Specifically the POSIX parser (http://www.javaworld.com/article/2072482/command-line-parsing-with-apache-commons-cli.html)
It will enable you to specify POSIX style command line arguments (--buy {value} --sell {value})...

main method String[] args issue

I'm reading Sams Teach Yourself Java in 24 Hours and came across this code:
class NewRoot {
public static void main(String[] args) {
int number = 100;
if (args.length > 0) {
number = Integer.parseInt(args[0]);
}
System.out.println(“The square root of “
+ number
+ " is "
+ Math.sqrt(number));
}
}
But in order for the code to be compiled, the writer enters 169 in the Arguments field in the
Run>Set Project Configuration>Customize
menu (in NetBeans IDE).
So my question is: what's the purpose of the specific field? Does 169 means something or is it just a random number? It's a pity the writer doesn't say anything about it!
The author is giving you an example of running a program with arguments given via the terminal. This is usually done in your terminal or command prompt by running the code as such
javac ProgramName.java
java ProgramName <arguments>
Since you are writing and running your program in Netbeans, and wont be using the terminal, you can configure to run the project with a given command line argument. This is what you are doing in the netbeans menus.
The String "169" only has meaning for the given program. The author is trying to demonstrate how the program will run given a command line argument, in this case he sets it to an arbitrary value "169."
In your code you are taking this String and turning it into an int.
The number 169 is almost certainly meaningless and arbitrary; it is used by the author merely as an example. Now let's break the code down line by line to address your concerns.
args contains any command line arguments as an array of strings:
public static void main(String[] args) {
The author declares a variable of type int and calls it number. He assigns an initial value of 100. This would appear to be a randomly selected number to demonstrate the concept - a common approach in programming books.
int number = 100;
He then checks if there were any command line arguments supplied; if there were, args.length will be greater than zero:
if (args.length > 0)
If there is a command line argument he parses the first argument into the number variable (this operation could fail by the way if you supply a non-numeric first argument):
{
number = Integer.parseInt(args[0]);
}
Note that if there is no command line argument, number is not overwritten. So, call the program without a command line argument and it will display the square root of 100. Call it with an argument of 169 (surely another number picked out of the air) and it will show you the square root of 169.
Command line arguments will be packed into args; input from keypresses etc after the program has started will not.

What is exactly args and how do i used it? [duplicate]

This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 9 years ago.
I am a new programer and I'm just starting to learn the basics of Java and I'm trying to understand what exactly "args" stands for in "public static void main(String[] args)".
I found that's it's connected to command line arguments, which I don't understand. I would like to know what "args" means.
Thank you.
When you run a Java program, it usually looks like this:
java MyProgram
However, you also have the option of including command-line arguments. For example, if your program adds two numbers, you could set it up to take input like this:
java MyProgram 12 47
In this case, arr would equal ["12", "47"]. Having input work in this way is useful because it makes it easier to automate the running of your program through batch files or the like.
args is an arbitrary name for command line arguments. Running a java class file from the command line will pass an array of Strings to the main() function. If you want to handle extra arguments, you can check for keywords at certain indices of args and perform extra functions based on them.

Input parameters in java

I was wondering why do Java programs take parameters only in the form on Strings from the command line when they are run? I have read that if the parameters are declared as int, it still converts the int into String. Why does this happen? And is there any way to accept only int values from the command line when running a java program?
Strings are more versatile as they can hold any value and can even be an representative as an int. If you want to pass an int in the command line you can convert the string to and int yourself.
int val = Integer.parseInt(arg[0]);
The valid signature for the main method is
public static void main(String[] args)
no other argument structure will be seen as a main function.
I have read that if the parameters are declared as int, it still converts the int into String.
You have read that incorrectly. If the main() method takes anything other String[] args, it won't be recognized as a valid entry point by the JVM.
If you wish to take integer arguments, your main method still has to accept String[] args, and you have to perform the conversion yourself.
You passing chars from command line anyway (just because there is no "integers" on keyboard). So, you need to convert this char arrays (which are wrapped into String) into integers.

Categories