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.
Related
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/
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is “String args[]”? in Java
So I recently (well, three days ago) started teaching myself Java, with absolutely zero previous programming experience unless you count HTML/CSS.
Now I've been looking through both books and online tutorials, including the Sun tutorials. I don't quite understand what the purpose of (string args[]) in a method is.
What I've got from looking online is that when using the console to run a program, it substitutes whatever comes after ">Java myprogram" in place of the "args".
Firstly, is that correct? If so, why would you do that?
Cheers!
The String[] args which can be written as String args[] or String ... args is an array of the arguments you gave the program.
why would you do that?
So you can give your program inputs on the command line. It isn't used in Java programs so often but it is quite commong for command line utilities to take arguments e.g.
In this case the MyClass.java is an argument.
javac MyClass.java
Or like the following has three arguments.
java -cp . MyClass
This is, more or less, correct. Every whitespace-separated word that comes after java Program is stored into an array of Strings, which happens to be called args.
An example on how to use this for your benefit:
public class Test {
public static void main(String[] args)
{
if(args.length > 0)
{
System.out.println(args[0] + "\n");
}
}
}
Compile this with:
> javac Test.java
And then run it:
> java Test Yes
"Yes" is then printed to your screen.
As you can probably understand from the question itself, I'm new to Java.
I was given an exercise to write a Java program which receives a character, prints it and the next character in the Unicode table.
Now, I have the solution to this exercise:
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
I understand basic idea of this code, but I'm trying to run this code in Eclipse I get an annoying error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MainClass.main(MainClass.java:9)
Note: I have yet to run a Java program that actually receives something as a parameter so I guess it's a stupid beginners' mistake... Here is the full code that I tried to compile in Eclipse:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
}
Thanks in advance
Select "Run -> Run Configurations" from the menu.
Search for you project in the list on the left and select it.
Select the "Arguments" tab on the right.
Write the argument you want to pass to the programm in "Programm arguments".
Click "Run"
Right click on your java file in project explorer of your eclipse. Then Run As> Run Configuration
Then you will get a window. Like-
Click on Arguments Tabs, and then write some text there, may be a character.
And then Click on Apply button and Run Button.
The default run configuration in Eclipse runs a Java program without any arguments, hence the ArrayIndexOutOfBoundsException. Your code is trying to get first element of the args array when there aren't any!
You can edit the run configuration to provide the arguments to run your program with. Then it should not throw this exception.
However, a good practice is to check the size of array before accessing it's elements, more so when the array is coming as an argument from outside of your code.
This is a great question with some very good answers. I would like to add some pointers about how to debug your own program. Debugging is as important (if not more important) than writing code.
For one thing, Eclipse has some great debugging features. You can use this debugger to find problems in your code. I suggest that you learn how to use it. In particular, you can set watches for variables to see what value they have as you step through the execution of your code.
Alternatively, you can add calls to System.out.println() to print out the values of any variables. For example, adding the following line at the beginning of your code might help you narrow down the problem:
System.out.println(args[0]);
This would also give an ArrayIndexOutOfBoundsException if no command-line arguments are given. Then you could do something like
System.out.println(args.length);
which would print out 0. This then gives you a clue as to where the problem is.
Of course, even when you get to this point, you still might not know how to solve the problem. This is where sites like StackOverflow come in handy.
Good luck with your Java experience. Please come back when you need more help.
If your Run Configurations are in place (as already shown in above answers):
Shortcut to Run a class is:
Ctrl + F11
First of all, I read all related topics and none of them answered my question.
I am developing a program in Java using Eclipse and I need to pass some arguments to the program continously after it starts.
For example somehow i need to give it this command by command line after it starts to execute:
CreateTable Students 2 10 10
And then I must be able to give more commands such as :
AddRecord Students Jack 1456
Run Configurations of Eclipse does not solve the problem since I can give arguments to the program only once by using Run Configurations. But I need to do it multiple lines?
Anyone has a solution? Thanks in advance
It doesn't seem to be possible in Eclipse according to this Question (which also lists possible workarounds). Update it's not possible to allocate System.console(), that much is true
But it does work with System.in (thanks Stephen C):
Scanner scanner = new Scanner(System.in);
String line;
while (true) {
System.out.println("Type something please:");
line = scanner.next();
System.out.println(line);
}
Sounds like you should read a sequence of commands from an inputstream, which might be connected to a Scanner (for live input) or a file (for runtime testing.)