java.lang.ArrayIndexOutOfBoundsException: 0 - java

I am learning java using a book. There is this exercise that I can't get to work properly. It adds two doubles using the java class Double. When I try to run this code in Eclipse it gives me the error in the title.
public static void main(String[] args) {
Double d1 = Double.valueOf(args[0]);
Double d2 = Double.valueOf(args[1]);
double result = d1.doubleValue() + d2.doubleValue();
System.out.println(args[0] + "+" + args[1] + "=" + result);
}

Problem
This ArrayIndexOutOfBoundsException: 0 means that the index 0 is not a valid index for your array args[], which in turn means that your array is empty.
In this particular case of a main() method, it means that no argument was passed on to your program on the command line.
Possible solutions
If you're running your program from the command line, don't forget to pass 2 arguments in the command (2, because you're accessing args[0] and args[1])
If you're running your program in Eclipse, you should set the command line arguments in the run configuration. Go to Run > Run configurations... and then choose the Arguments tab for your run configuration and add some arguments in the program arguments area.
Note that you should handle the case where not enough arguments are given, with something like this at the beginning of your main method:
if (args.length < 2) {
System.err.println("Not enough arguments received.");
return;
}
This would fail gracefully instead of making your program crash.

This code expects to get two arguments when it's run (the args array).
The fact that accessing args[0] causes a java.lang.ArrayIndexOutOfBoundsException means you aren't passing any.

Related

ArrayIndexOutOfBounds Exception for program compiled using Java

I am new to java. My code is:
public class Hi {
public static void main(String[] args) {
System.out.print("Hi, ");
System.out.print(args[2]);
System.out.print(",");
System.out.print(args[1]);
System.out.print(", and");
System.out.print(args[0]);
System.out.println(".");
}
}
I get the following exception upon running this program:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Hi.main(Hi.java:5)
I would be glad to know why I had got this exception and how to resolve it.
You are passing parameters which is less than 3, thats why you are getting this error.
try like below command,
java hi test test test
Either you dint passed command line arguments while executing the program or args.length < 3
You would have got this exception if you had tried to run this program providing 2 or fewer arguments.
args[0] will be the first index of the array.
args[1] will be the second index.
args[2] will be the third index of the array.
This is because array index starts with 0 and ends with n-1 for arrays in Java. (n is the size of the array).
Command line way
This program will run fine, if you run the program as
java Hi Demo Test Argument
Here Demo is at args[0], Test is at args[1] and Argument is at args[2].
Using Eclipse IDE
Right click on the class file.
Select Run As and select Run Configurations
Double Click on Java Application
Go to the Arguments tab and provide three arguments in the Program
Arguments textarea separated by spaces as shown in the image below.
Now click on Apply and then on Run

What Exacly (args.length>0) means?

This may be simple to you people but as i am new to java, so i want know actually what is
going on in the following part?
if (args.length > 0) {
file = args[0];
}
public class DomTest1 {
public static void main(String[] args) {
String file = "test1.xml";
if (args.length > 0) {
file = args[0];
}
}
}
Those are called command line arguments , which you get as a String array in your program. Here is the Oracle tutorial
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
Hence the below code :
String file = "test1.xml";
if (args.length > 0) {
file = args[0];
}
Checks to see if the length of the String[] args is greater than 0 , which means it checks if any command line argument was entered or is the array empty. If command line arguments were entered , then assign file the first element of that array , or else default file to test1.xml. You can run your class as :
java DomTest1 someFileName.someExtension
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the DomTest1 application in an array that contains a single String: "someFileName.someExtension".
args is an array of Command Line arguments
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings
Where args is an array and if (args.length > 0) is the condition cheking that array is empty or not .
You are making String reference here and put the value in it.
You first value is> test1.xml. It is a name of a file but you are putting into String
as String(It means "test1.xml"). and then taking value from command line argument. And overriding value of you string reference by command line location 0.
so you reference value will be always command line 0 location value if you do not pass any value then it will give you text1.xml
The main() method is where the execution of java program starts.The place where all parameters passed to main() method are String args[]. It is basically a String array. The variable name can be changed to something else other than using only args, You may use String var[] or `String datas[] or something else.
Now, Coming to the if condition checking in your program if (args.length > 0).
I will explain the fundamental of why arg.length is so.
When a java program is executed from command line or similar terminal, it is run as java customName. Let's say the parameters you want to pass to java program as java customName param1 param2. The arguments are passed along with command line.Now the interpreter in java interprets these paramenters(i.e param1 param2) and passes them to main() method of the program. These parameters are stored in the args[] String Array.
Now while running java program args[0] and args[1] will be allowed.If no arguments are passed then the value of args[] will be null and will be still be identified as String array object with null parameters(no elements).
In that case the args.length will be equal to 0.
That line is checking to see if arguments were actually entered on the command line.
If any are entered, the first one is the name of the file.
If none are entered, test1.xml is the default.
The args.length value is the number of items in the args array.
If you pass no command-line arguments, you will always get "There are 0 command line arguments".
thats why you checking
if (args.length > 0)
But try running the program like this: java PrintArgs hello my name is mikki2 The words after java PrintArgs are called command line arguments because they are arguments passed to your program from the command line

Exception in Java program

When I run the code give below, the following message showed up. What does it mean and how do I overcome it in this instance?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ifDemo.main(ifDemo.java:5)
public class ifDemo {
public static void main (String [] args)
{
int x= Integer.parseInt(args[0]);
double half=0.0;
if (x!=0)
{
half=x/2.0;
System.out.println(x+ "/2 = "+half);
}
if (x==0)
{
System.out.println("The value of x is "+x);
}
int y=x*5;
char grade='F';
if(y>=85)
{
grade='A';
}
if (y>=70 && y<85)
grade='C';
System.out.println("y= "+y+ "and grade equal to "+grade);
}
}
Essentially this means that you are trying to access an index in the args array that doesn't exist.
In your code you have:
int x= Integer.parseInt(args[0]);
And this error is complaining that you actually don't have an index 0 in your args array, i.e the array is empty.
To remedy this, you need to pass your program command line arguments when it is run, in other words, run it as java ifDemo Some Integer Here
For further reading try this, also Google is Your Friend
While running the code you may not be passing any value that x can get a value from arg[0].
Pass value while running the code, this will solve the issue.
Are you using the command-line for executing it?
If you are trying to run the program in Command Prompt then be sure to provide the command line argument. I tried running the program and got no errors.
When you are running the program from the command line you are forgetting to add an argument as so:
java ifDemo.class 1
So essentially the variable args contains absolutely nothing. Therefore, when you try to get the value of args[0] it is throwing the ArrayIndexOutOfBoundsException. You can read more about it here.
What you could add is a form of validation that checks if the user has entered a number and, if they have not, tell them. The code for that would look something like this:
if(args == null || args.length == 0) {
System.out.println("Please enter a number as a command line argument.");
System.exit(0);
}
Or you could look into getting input from the console and using a do while loop for validation of that. If you want a code example just let me know!
int x= Integer.parseInt(args[0]);
In that line above, you are indexing into an array, assuming it has at least 1 element. Are you sure it has one element in it? Are you calling your java program and passing in a number?
int x= Integer.parseInt(args[0]);
This is trying to read the first command line argument.
It will fail with the exception you describe when there are none.
You should update the program with a check for the command line arguments and add an error message if they are amiss.
Run it as java ifDemo xxx where xxx is some integer.
args is an array of String which are called Command line arguments. So, if you run your program from command line as java ifDemo 10 12, then args will contain [10,12] , args[0] will be 10, args[1] will be 12 and args.length will be 2.
This line is throwing an error because you didn't run the program with command line arguments.
int x= Integer.parseInt(args[0]);
args is empty and you are trying to access the 1st element of the array which causes ArrayIndexOutOfBoundsException, thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
You are not passing an integer as command line argument int x= Integer.parseInt(args[0]);
args[0] is assigned a value by command line arguement.
Compile and run program in following way:
javac ifDemo.java
java ifDemo 23
When you run the program, args[0] is 23.
Earlier as you were not providing any argument by command line, so args[0] was not set and you were getting an array-outofbound-exception.

java.lang.ArrayIndexOutOfBoundsException issue

I am a new Java programmer. The following is my code:
public static void main(String[] args) throws Exception {
BPM2SampleProcessor processor = new BPM2SampleProcessor();
processor.setSampleSize(1024);
EnergyOutputAudioDevice output = new EnergyOutputAudioDevice(processor);
output.setAverageLength(1024);
Player player = new Player(new FileInputStream(args[0]), output);
player.play();
log.log(Level.INFO, "calculated BPM: " + processor.getBPM());
}
It shows a runtime error as
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 in the following line: Player player = new Player(new FileInputStream(args[0]), output);
Please explain what the error is and how to overcome it.
Are you running your code from the command line or from an IDE like eclipse?
Every main method has a String[] (usually called args) which you can see in the first line of your code.
The program is trying to use args[0] as the name of the file to open. (which you supply from the command line, or configure in the IDE). But right now the args variable doesn't have anything in it. Try replacing args[0] in your program with a string representing the file you want to open. You will have to make sure that you get the correct path.
You're likely not passing any command line parameters into your program when you run it, so the size of args is 0, and args[0] will throw the exception your seeing. The solution is to pass a parameter, presumably an appropriate file name in when you run this program by calling
java MyProgram myfilename.ext
When you run the program you have to give an argument. the args[0] is coming from the user input which you havent given. something like java MyProgram 5
You are not passing the argument required args[0] and hence it is throwing the error.

java netbeans commadline argument passing

I am passing a command line argument using Netbeans but I get an ArrayIndexOutOfBoundsException.
My code is:
public class CmdLineArgumentPassing
{
public static void main(String args[])
{
System.out.println("Count : " + args.length);
System.out.println("i : "+args[0]);
}
}
The output is:
Count : 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Right mouse click on the project, select Properties, go to the Run page, add the command line arguments.
As your output is Count : 0 then the args array has a length of 0 which means no arguments are being passed.
When you try to access the first argument using arg[0] you get an Exception as you are trying to get a member of the array which does not exist. In this case you're trying to get the first member of an empty array. Remember array indexes start at 0 and go to length - 1.
As args is empty it means the problem is with Netbeans passing your arguments not with your code, so my guess is that Netbeans is not configured properly.
I had the arguments set on the project properties/run/arguments but I was runing the class directly (right click over the class file -> run) , so no arguments from the project where being passed. The solution was to make right click over the project and then select the option "Run". The the arguments where passed.
Click on Final proj and run and not the main project for netbeans 6.9.
U will get the answer.

Categories

Resources