in command line arguments i got Exception in the thread main java.lang.ArryINdexOutOfBoundsException. How can i overcome this?
class p
{
public static void main(String a[])throws Exception
{
int n= Integer.parseInt(a[1]);
System.out.println(n);
}
}
If you call the program with only one parameter, you have to use Integer.parseInt(a[0]);, because arrays in java are zero bases.
Also you should check the length of a before accessing an entry.
You can give the two parameters from command prompt then your code will be successfully run like java className parameter1 parameter2 then you can access second parameter by using a[1].
other wise change a[1] to a[0] for first parameter.
Related
In:
public static void main (String [ ] args)
How to set the value parameter variable args of the main method as an array of String?
The args are optional command line values.
java MyProgram --arg1 --arg2
could be accessed as
args[0] == "--arg1"
args[1] == "--arg2"
Value is passed as command line arguments.
For ex, you have this program(Cmd.java):
public class Cmd
{
public static void main(String agrs[])
{
System.out.println("Values are:"+args[0]+" and "+args[1]);
args[0]="New1";
args[1]="New2";
System.out.println("Modified values are:"+args[0]+" and "+args[1]);
}
}
Compile it like:
javac Cmd.java
Execute it like:
java Cmd Value1 Value2
Output will be:
Values are Vaue1 and Value2
Modified values are New1 and New1
Hope you got the point!
BONUS:
If you don't pass any values during execution the program will throw an ArrayIndexOutOfBoundsException.
You may want to handle that!
Read more about Command Line arguments at The Java tutorials (Oracle docs)!
When you execute your java program in command line you can provide arguments to the executable:
java MyClass arg0 arg1 arg2
In Java the word args contains the command-line arguments that are given in input to your program as an array of String Objects.
That is, if you run java AnExample a b, args will contain ["a", "b"].
So, if you want just to print out the contents of args, you can simply loop through them:
public class HelloWorld {
public static void main( String[] args ) {
for( int i=1; i < args.length; i++ ) {
System.out.println( args[i] );
}
}
}
For a deep explication of the Java args you can read this interesting presentation from Emory university.
You can set an array of Strings when you call the program.
java MyClass args0 args1 etc
If you are using Eclipse then this is done under Project->Run Configurations/Debug Configurations. Click the Arguments tab and enter your arguments in the Program arguments box.
The String args[] contains all the arguments you pass to a Java program when you start it with a command line.
Example command to launch a Java application:
java MyApp arg1 arg2
What we have done in the example above is we passed 2 arguments to our MyApp java application ("arg1" and "arg2").
You can now use them however you want.
yup..
just compile your code by
javac <class name> args0 args1 ..
Description
I have a beginner's-level program. My goal is to pass an argument in at runtime for the first time.
Proposed questions
Describe the error in greater detail?
How are errors like this traced and repaired?
I've used google and StackOverflow. Should I be using a different resource to help with errors like this in my beginner programs?
My code
class sayagain {
public static void sayagain(String s){
System.out.print(s);
}
public static void main(String[] args){
sayagain(arg);
}
}
Compile error
print2.java:11: error: cannot find symbol
print2(arg);
^
symbol: variable arg
location: class print2
1 error
Correct
arg is not defined. Maybe you mean sayagain(args[0]), which will print the first argument in the main method.
Explanation of string array types-and-indexes
args is a string array, so to get the first argument you need to access the first element in the array: [0].
Warning
You will be given an index out of bounds error if you do not include any arguments when you call the main method.
Example input: >java sayagain
Example output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at sayagain.main(sayagain.java:11)
Variable plurality
There's no built-in function to discover arg as the singular of args. Variables may be anything within the specification of the formal language, even asdfsfaeef. It is much better practice to use a descriptive name; therefore, people tend to use plural form when naming arrays.
It looks like typographical error.
you have passed arg :- s is missing from the name as the argument you recieved in main method is args.
sayagain(arg);
However if you pass 'args' to your method it still give an error as args is an array type and your function is looking an String type. So the correct call for that function would be.
sayagain(args[0]);
Check the args length before calling this function otherwise it may throw an ArrayIndexOutOfBoundException if parameter not passed.
My own spin
Correct: System.out.print(args[0]);
Incorrect: System.out.print(args); //wrong type.
Incorrect: System.out.print(args[1]); //wrong index.
Incorrect: System.out.print(arg); //not a variable.
Incorrect: System.out.print(arg[0]); //typo (see above).
In Java, source code is compiled to class files using javac sayagain.java, which in turn creates a sayagain.class which is essentially what the JVM (Java Virtual Machine) can understand and execute.
To run the sayagain.class that the javac command generated, you'll use java sayagain
You can also pass arguments, seperated by spaces, to the class that you are running, like so:
java sayagain Hello World !
These arguments is passed to the args array which you defined in your main class, which is the method that will be called first. (You could have called it listOfArguments, like below, and it would have made no difference)
To access any object contained within an array, you use []. Number starts at 0 and ends and length-1. Here is an altered example of your code:
public class sayAgain {
//Eventhough there is two say methods, one takes a String parameter, and one takes an Integer parameter, thus they are different
public static void say(String s){
System.out.print(s);
}
public static void say(int i) {
System.out.print(i);
}
public static void main(String[] listOfArguments){
//First argument, starting at 0 - Hello
String arg1 = listOfArguments[0];
//Second argument - World
String arg2 = listOfArguments[1];
//Second argument - 3
String arg3 = listOfArguments[2];
//arg3 is a integer but is saved as a String, to use arg3 as a integer, it needs to be parsed
// Integer, is a class, just like your sayAgain class, and parseInt is a method within that class, like your say method
int count = Integer.parseInt(arg3);
//Print each argument
say(arg1);
say(arg2);
say(arg3);
//Use the converted argument to, to repeatedly call say, and pass it the current number
for (int t = 0; t < count; t++) {
//The variable t is created within the for structure and its scope only spans the area between the { }
say(t);
}
}
}
Hope this helps :)
This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Why does main method in Java always need arguments?
(8 answers)
Closed 9 years ago.
I added the following code to a new class I created in Java:
public static void main(String[] arguments) {
I understand what public, static and void mean, but what does (String[] arguments) mean?
Your main() method can take input parameters of type String if your program is run through a console like
java YourClass arg1 arg2
Now, within main() if you iterate the String [] like
for (arg : arguments)
System.out.println(arg);
it should print
arg1
arg2
Demo :
public class AddTwoNumbers {
public static void main(String[] args) {
if(args.length == 2) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("a + b = " + a + " + " + b + " = "+ (a + b));
} catch (NumberFormatException e) {
System.err.println("Invalid Input: Please enter numbers.");
}
} else {
System.err.println("Missing Input: Please enter TWO numbers.");
}
}
}
You can run this on your console as
java AddTwoNumbers 2 3
and it should print
a + b = 2 + 3 = 5
It literally means "an array, where every element inside of it is at least a String, which we will name arguments".
In the context of the rest of the line, the method main takes as input, "an array, where every element inside of it is at least a String, which we will name arguments"
Since this is the public static void main(String[] arguments) method call, there is a special "exception to the rule" of normal parameter passing. Methods that look like this are one of the very few times when your input is not defined in some other part of your program. Instead the Java Virtual Machine constructs the input into this method, from the command line arguments you gave the JVM.
It means that the function expects an array of strings.
String[] arguments is the array for run time argument to your java program. If required you can pass arguemnts to your java program like this:
java yourJavaMainClass args1 args2
In your java code you can use the arguments provided by simply iterating over this array.
arguments[0] // this should give you the args1
It's the array of parameters that you may pass to your program during the execution. Ex:
java YourClass param1 100 X
In your runtime, you'll have this array
System.out.println(args.length); //prints 3
System.out.println(args[0]); //prints param1
System.out.println(args[1]); //prints 100
System.out.println(args[2]); //prints X
These are the parameters that the main function expects.
String [] arguments is a java array of String objects. This means that the main function expects an array of Strings. This array of strings typically holds all command line parameter arguments passed in when the program is run from the command line.
From the command line
java className stringOne stringTwo
In the program
Note : means in .. So read this as for stringObject in arguments
for (stringObject : arguments) {
System.out.println(stringObject);
}
Or if you know the exact amount of Strings that will be in arguments is two then
System.out.println(arguments[0]);
System.out.println(arguments[1]);
Output->
stringOne
stringTwo
Hope this helps! Good luck learning Java
Run the program using command line and the input provided there gets stored in obj array. So if you run the class as java className a1 a2 then object array will have a1 and a2 as elements.
Or if you are using eclipse IDE the go to run/debug config and do as shown
iv'e been trying to learn basic java programming for the last 2 days, and I encountered an issue i can't figgure while viewing the following code:
class DayCounter {
public static void main(String[] arguments) {
int yearIn = 2008;
int monthIn = 1;
if (arguments.length > 0)
monthIn = Integer.parseInt(arguments[0]);
if (arguments.length > 1)
yearIn = Integer.parseInt(arguments[1]);
System.out.println(monthIn + "/" + yearIn + " has "
+ countDays(monthIn, yearIn) + " days.");
}
}
I can't understand the line if (arguments.length > 0)
what does arguments mean? Where did the value come from?
I can't understand the line "if (arguments.length > 0) what does "arguments" mean? where did it value came from?
It came from the method declaration:
public static void main(String[] arguments) {
That declares a parameter called arguments. For a normal method call, the caller specifies the argument, and that becomes the initial value of the parameter. For example:
int foo(int x) {
System.out.println(x);
}
...
foo(10);
Here, 10 is the argument to the method, so it's the initial value for the x parameter.
Now a public static void method called main in Java is an entry point - so when you run:
java MyClass x y z
the JVM calls your main method with an array containing the command line arguments - here, it would be an array of length 3, with values "x", "y" and "z".
For more details, see the relevant bits of the Java tutorial:
Passing information to a method or constructor
Command-line arguments
arguments are the command line options given to your java program when it runs. They are stored in an array so calling arguments.length gives the number of command line inputs to your program.
They are passed in like this on execution
java program argument1, argument2, argument3
In this case arguments.length would return 3 as there are 3 command line arguments.
In this case arguments is the variable name used for array of Strings you provide as input on execution,
i.e.
java DayCounter 1 2010
In the following code excerpt:
public static void main(String[] arguments)
String[] means an array of Strings with a variable name of arguments. Java uses this function prototype for main as default. See here for a tutorial: http://docs.oracle.com/javase/tutorial/getStarted/application/index.html
So when you reference length in arguments (arguments.length), you are looking "inside" the array of Strings finding the length of the array (using a built-in function of Java Strings to do so)
They come from the command prompt. When you start to run a program, you can say:
java program arg1 arg2 ...argN
The args go immediately after the program name.
- Usually parameters and arguments are used interchangeably, but they are different.
I will take an example to explain this:
public class Test{
public void go(String s){
}
public static void main(String[] args){
Test t = new Test();
t.go("Hello");
}
}
- In the above code variable s which is of type String in the line public void go(String s) is the Parameter.
- Where as "Hello" which is of type String in the line t.go("Hello") is an Argument.
- The elements in method definition or declaration are Parameters, where as the elements passed in the method call are Arguments.
Arguments is a list of Parameters that can be passed to your Java Programm at start up.
if (arguments.length > 0) checks if any arguments have been provided.
As otherwise you will be trying to access an empty array and get and index out of bounds exception.
Also there are pleanty of tutorials out there, that can help you.
Have a look at Oracle's essentials guide, here about CMD Line Arguments.
arguments is passed in to the main method
public static void main(String[] arguments)
in this case it means an array of values that can be passed to this method. Usually this is the arguments that you pass to a program from command line or from a shortcut and then you can use them in the program to change the logic flow.
First Understand the meaning of code at hand.
It tells you the number of days in a given month of a year. So obviously when you run the code you need to have a year value and the month value as given values.
In this case month value and year value as provided during code execution time become the argument. In this case the word "argument" is used as such but you can use x or y or xyz to name a variable, as you know.
Java accepts the arguments as the String array. So prior to using them as Integer you need to parse them, that's what has been done in the above code.
Eg
class WelcomeYouself{
public static void main(String[] args){ //Here insted of arguments,the word args is used.
System.out.println("Hello " + args[0]);
}
}
Now when you run this you pass your own name as argument.
java WelcomeYourself Feynman;
// This how you run or execute the java code passing your name as the "argument". Of course it is presumed you are Feynman.
I am trying to detect whether the 'a' was entered as the first string argument.
Use the apache commons cli if you plan on extending that past a single arg.
"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."
Commons CLI supports different types of options:
POSIX like options (ie. tar -zxvf foo.tar.gz)
GNU like long options (ie. du --human-readable --max-depth=1)
Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
Short options with value attached (ie. gcc -O2 foo.c)
long options with single hyphen (ie. ant -projecthelp)
public class YourClass {
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("a")){
//...
}
}
}
Every Java program starts with
public static void main(String[] args) {
That array of type String that main() takes as a parameter holds the command line arguments to your program. If the user runs your program as
$ java myProgram a
then args[0] will hold the String "a".
Command-line arguments are passed in the first String[] parameter to main(), e.g.
public static void main( String[] args ) {
}
In the example above, args contains all the command-line arguments.
The short, sweet answer to the question posed is:
public static void main( String[] args ) {
if( args.length > 0 && args[0].equals( "a" ) ) {
// first argument is "a"
} else {
// oh noes!?
}
}
Command line arguments are accessible via String[] args parameter of main method.
For first argument you can check args[0]
entire code would look like
public static void main(String[] args) {
if ("a".equals(args[0])) {
// do something
}
}
Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).
Try to pass value a and compare using the equals method like this:
public static void main(String str[]) {
boolean b = str[0].equals("a");
System.out.println(b);
}
Follow this link to know more about Command line argument in Java
As everyone else has said... the .equals method is what you need.
In the off chance you used something like:
if(argv[0] == "a")
then it does not work because == compares the location of the two objects (physical equality) rather than the contents (logical equality).
Since "a" from the command line and "a" in the source for your program are allocated in two different places the == cannot be used. You have to use the equals method which will check to see that both strings have the same characters.
Another note... "a" == "a" will work in many cases, because Strings are special in Java, but 99.99999999999999% of the time you want to use .equals.
Command line arguments are stored as strings in the String array String[] args that is passed tomain()`.
java [program name] [arg1,arg2 ,..]
Command line arguments are the inputs that accept from the command prompt while running the program. The arguments passed can be anything. Which is stored in the args[] array.
//Display all command line information
class ArgDemo{
public static void main(String args[]){
System.out.println("there are "+args.length+"command-line arguments.");
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]:"+args[i]);
}
}
Example:
java Argdemo one two
The output will be:
there are 2 command line arguments:
they are:
arg[0]:one
arg[1]:two