main method String[] args issue - java

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.

Related

Index 0 out of bounds for length 0 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
Here i am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
System.out.println(input);
while(true){
if(args[0].equals("k")){
System.out.println("k");
}
}
}
You need run the code on cmd as java MyProgram abc xyz then args will contain ["abc", "xyz"].Maybe you are not doing that right now and therefore getting the error.
You need to provide Command Line Arguments like so:
java MyClass k foo bar
These arguments are passed to the array args[] which will then contain {"k", "foo", "bar"}
Therefore args.length will be 3 and args[0] will be k
If you are executing through IDE and not setting arguments OR not passing command line arguments while running through cmd, you'll get this error.
But for this program, even if you pass arguments, it will run in infinite loop probably as while condition is always true.
You are executing this java class without arguments. In that case, args[0] does now exist, and thus the Exception with Error message.
You can modify the if in this form:
if(args[0].equals("k") && args.length > 0 )
so you do not get exception with message
Index 0 out of bounds for length 0
Your program is producing output without error, when Running the program with argument "k" produces the infinite look of printing k. For this you need to run command the java printKjavaFile k , or start it from IDE with this argument.
You are doing 2 things at the same time:
ask for user input via stdin, when the program is running already
parsing the args[], which should be given when the program starts to run
and expect they work together. But they are different.
I suppose you run the app like: java MyClass without adding extra args after this. You can:
provide arg k after java MyClass, so args[] becomes a non-empty array
stop trying to use args, but just focus on input, which is the line you read from user input.

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.

Java: Making an Optional Command Line Argument

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/

java jar accept multiple arguments on runtime

I have a java jar that need to accept about 3 arguments but I want to pass them as a Q&A type like the following:
1st step run java jar
java -jar myTest.java
2nd step ask questions and wait for answers:
Hi, how old are you?
I type my answer that accepts it and then ask the 2nd question:
nice! what is your name?
type my second answer and the get a third question and so on. how do I achieve this? I know that I can pass arguments to main but what I found is that I have to pass them all when I first run the jar not like what I'm looking for.
Any ideas?
Thanks!
the way to interact with an application depends of the logic in the application itself...
if you need to give parameters that the application needs from the start point then you give those as soon as you run the application
java -jar myTest.java
all those parameters are getting passed to the string[] parameter in the public static void main method...
in your case, (and if I got the question right) you will need more information from the user, and this is given at runtime... so you need another way to do that like Scanner class allowing you to read input from the terminal too...
Use the Scanner class and read the user input from the console..
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
String input = sc.nextLine();
System.out.println("Hi, " + input + ", where are you from");
input = sc.nextLine();
System.out.println("Ohh, " + input + " is nice place I guess!");
System.out.println("and how old are you??");
...
}
It seems that you are mixing up concepts.
Command line arguments are those strings that you see as String[] args parameter to your main method!
But you want the user to provide "more" input to your application, the typical way is to read them from "stdin" (see here to learn how to do that).
Those two are fundamentally different things; and you should first clarify which one you really intend to use (given your example ... probably the "stdin" option).
Try reading the Java IO tutorial here:
https://docs.oracle.com/javase/tutorial/essential/io/cl.html

how to reuse previous variable value after closing program

public class UseVariableValueAgain{
public static void main(String args[]){
int x=6;
int y=7;
int LastValue=0;// for first time
LastValue=x+y+LastValue;
System.out.println("result"+LastValue);
Scanner scan = new Scanner(System.in);
int x1=scan.nextInt();
int y1=scan.nextInt();
int LastValue1=0;
LastValue1=x1+y1+LastValue1;//for first time
System.out.println("REsult using Scanner="+LastValue1);
}
}
Ressult=13
5
6
Result using Scanner=11
when i execute this program i got 13 output by default and by using scanner
i enter 5,6 and output is 11 , Now I want to use (13,11)values for next
time when i re-execute the program. but it give same result
Your options in order of easiness:
1) Next time when you invoke the program, pass the values at the command line.
java UseVariableValueAgain 13 11. You will have access to these values via args[] array now. Keep in mind you will have to parse this to integer as args is a String array.
2) Write these values to a file. (eg using BufferedWriter) and read it in the program using Scanner or BufferedReader;
3) Write the value to a database table. Read the values from the table in your program.
In all these options, you will have to check if this is a re-run by employing appropriate if-else conditions to check if the value needs to be read from user input or if it needs to be determined.
If you are learning Java, I recommend trying all three options in that sequence.
You need to write the previous value in a persistent storage(like file).

Categories