String[] args parameter: java.lang.ArrayIndexOutOfBoundsException - java

Hi i am a java learner and trying to make this program for add two number.
While running this i am getting this error msg..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at addnumber.main(addnumber.java:16)
Java Result: 1
public class addnumber{
public static void main(String[] args) {
String x,y;
int a,b,c;
x=args[0];
y=args[1];
a=Integer.parseInt(x);
b=Integer.parseInt(y);
c=a+b;
System.out.println(c);
}
}
I know i can use Scanner class or string builder class however whats wrong with this code?

If you use the args-array you have to give the programm some parameters from outside for example from the console.
So open the console and go to the directory where the .java file is and compile it manually with
javac Addnumber.java
Now you should see a .class file there.
Than write a call like this:
java Addnumber 5 9
your arguments would be 5 and 9.
Also write the classname in capitals

If your running with eclipse or any other working tool. then you have to set run configuration-arguments.
Suppose you run this code in command line then you have to run this code using the below command
java addnumber 2 4

Good Quastion, The Problem is in String[] args, this problem leads to find out what is the initial value of this Parameter as string? or in other words How is the IDEs call the main method? if you run this code in Netbeans or Eclipse by default will print this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
because by default the IDE call method with array of string with 0 length:
TheNameOfClass.main(new String[0]) // if you run it in some IDEs
>java Addnumber // cmd with no args?
In your case the exception will occur in line x=args[0]; because you invoke and you want to use some item in array out of range or grater than the length of the array.
Now you can configure it as example in eclipse to pass some Strings values as you need OR you need to compile and run the java class manual in a 'Command Prompt' and passed some of Strings values:
>javac Addnumber.java // compile it
>java Addnumber 1 77 // run it and passs some values to array in main method

Related

Array Index Out of Bounds - Class Name Convenction

I'm using the terminal in Mac to try and output some strings using javac. However there are some symbols that don't seem to work, for instance the dollar sign and asterisk:
public class BirdDisplay{
public static void main(String... args){
System.out.println(args[1]);
}
}
and then:
javac BirdDisplay.java
java BirdDisplay sparrow $someBird
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at BirdDisplay.main(BirdDisplay.java:3)
As far as I know $ is accepted in class names and is a valid identifier, what is the cause of this exception?
You're using it from a shell, where $ is doing environment/shell variable substitution. This has nothing to do with Java - it's how the shell is invoking the process.
Just put it in single quotes:
java BirdDisplay sparrow '$someBird'
Note that the use of a $ as a valid Java identifier is irrelevant, as you're not using it in any source code - the value $someBird purely being used as data in your program (or will be once you've prevented the shell from performing variable substitutions).
As Daisy pointed out, this is because you are running your program in the shell, where $someBird is interpreted as an environment variable. Because $someBird is not an environment variable, the shell replaces it with nothing and you have a command-line arguments array of length 1 instead of length 2. As such, your program has no value for args[1] and you get java.lang.ArrayIndexOutOfBoundsException. You can test this by running this code to print out the length of args:
public class BirdDisplay{
public static void main(String... args){
System.out.println(args.length);
}
}
And now when you do:
javac BirdDisplay.java
java BirdDisplay sparrow $someBird
You will see 1 instead of 2

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

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.

Different results when compiling with command prompt and BlueJ

I'm just starting Java ... again.
I just made a simple program
class first
{
public static void main()
{
System.out.println("Hello!");
}
}
This runs perfectly fine in BlueJ but it gives an error during run-time when running from command prompt.
This is the error
Exception in thread "main" java.lang.NoSuchMethodError: main
It's because I didn't give String args[] in the main parameter list
Till now, I used to give it subconsciously. I know that the string array contains all the parameter values when running but then why is it running in BlueJ?
(BlueJ is a student-friendly Java editor and compiler)
Your program is valid and will compile to the same thing whether you compile from BlueJ or from the command line.
However, blueJ will let you run any static method in a class (so you can test your functions) where as the command line java command will (only) look for a special main method to run. This main method tages a String array with all the command line parameters and your program should look like this even though you don't use these command line parameters:
class first
{
public static void main(String[] args)
{
System.out.println("Hello!");
}
}

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