How can I overcome ArrayIndexOutOfBoundException for Integer.parseInt(args[0])? [duplicate] - java

This question already has answers here:
String[] args parameter: java.lang.ArrayIndexOutOfBoundsException
(3 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I've seen below code in one of the video tutorial.There its executes fine but while I'm trying to execute in my system, it is compiling fine but I'm getting runtime error saying,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
class Test13
{
public static void main(String[] args)
{
int i = Integer.parseInt(args[0]);
System.out.println(i);
}
}
Can someone please guide me what's wrong with this code and how to rectify?
Thanks in advance!

It looks you're not passing in any parameters when you run your code.
From the Java doc for 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.'
Therefore you're trying to pull a value from the args array with an index 0, but the array is less than this size (in this case it's empty).
In order for this to prevent an exception being thrown you can apply a size check around the statement.
if(args.length>0) {
int i = Integer.parseInt(args[0]);
System.out.println(i);
}

if (args.length > 0) {
Integer.parseInt(args[0])
}

ArrayIndexOutOfBoundsException occurs when you try to access an element at an index which does not exist in the array.
For example: suppose int a[]={2,4,5,10,3} is an array.
the size of array is 5 and index starts from 0.
Which means your array ranges from index 0 to index 4 where element at index 0 is the first element i.e. 2 and element at index 4 is the last element i.e. 3
if you try to access any elements at an index which is not in the range 0 to 4 it will show you ArrayIndexOutOfBoundsException because no such index exists in the array.
Now in your case args is command line argument which means you have to pass parameters when you run your code.
If you are running your code from terminal then after java yourclassname you have to pass parameters.
For example: java yourclassname 10 20 30
here 10 20 30 are your command line arguments which get stored in your args array and args[0]=10 args[1]=20 args[2]=30
If you haven't passed any arguments during running your code your args is empty and therefore you will get ArrayIndexOutOfBoundsException
hope it helps you to understand the concept of command line arguments.

You should pass an argument to your main method when executing your application.
For example, in command line type:
java Test13 123
Then the output should be:
123
Moreover you can check argument availability by check args.length, like what Adam said in prev answer.

You are not passing any argument while running your program. If you are running from command line then write java Test13 1. you will be able to get your result in output.
If you are using eclipse to run your program then provide your arguments in "Run Configuration" ->Arguments tab -> Program Arguments text box -> give value as 1.
You will be able to run your program

This is a runtime error as you might have observed the compilation goes smoothly. Now, why this happens is because you have to pass the "argument" while you give the run command (as in 2)
1. You might have run this command, without actually passing the argument [0]:
When you do this, the array is of length 0 as there are no arguments passed to the main function. Which is how the program is expected to run according to your code.
$ java Test13
This will give an error output. The one you got, with Array exception.
2. Try running this command, that is, type a number along with your command:
$ java Test13 727
Here, you are passing the argument [0] as 727 to the main function. Which adds the element to your array. This should work fine.
Similarly, suppose you have more arguments like [0], [1] and [2] And, you forget to add numbers after '727' like in command 2. You must get a similar error. Unless you do this (giving three inputs for your command):
$ java Test13 727 837 9
This means you need to give your input during the run command itself. However, in C++ with 'cin' in your code, you can give input after running the first command. Java is safer this way, although no real threat exists here.
Hope this works for you :)

Related

Bash for loop in batch on list

I am trying to bash script where it executes following java jar command in batch mode on the basis of size of list.
i have a list of string with 54 states of USA.
list = [USA+CA,USA+TX,USA+TN...]
i need to execute following command in parallel with 4 instances having 4 values as input from list.
java -jar test-execute.jar --localities=USA+TX,USA+CA,USA+TN,USA+AB
wait till execution is complete for any instance, then start new instance of jar with next 4 states.
array=( USA+TX,USA+CA,USA+TN,USA+AB )
for i in "${array[#]}"
do
java -jar test-execute.jar --localities= ???
done
I am not able to understand how can i dynamically provide inputs from array into jar execution.
so,
i have list of size 54,
i need to run 4 java instances in parallel with each instance having 4 unique state as input from list of 54. , once these instances complete, then start next 4 instances with next unique 4 states per instance.
update:
i have list of 54 states , 16 core machine. each java jar instance will use 4 cores, so i can run 4 java instances at a time to to use 16 core machine .
16 core machine
java instance-1 4 states
java instance-2 4 states
java instance-3 4 states
java instance-4 4 states
wait till any of these instances complete, once completed, start new instance with next 4 states until all 54 states has been executed.
please help.
First of all, bash array must be assigned as a space separated list as:
array=("USA+AL" "USA+AK" "USA+AZ" "USA+AR" "USA+AS" "USA+CA" ...)
Then would you please try something like:
array=("USA+AL" "USA+AK" "USA+AZ" "USA+AR" "USA+AS" "USA+CA" ...)
for (( i = 0; i < ${#array[#]}; i+=4 )); do
echo java -jar test-execute.jar --localities="$(IFS=,; echo "${array[*]:i:4}")"
done
The for loop has a C-like syntax to increment the index by value 4.
The array slice ${array[*]:i:4} divides the array into sub-arrays
of every four elements starting with i'th index.
The last chunk with two elements are treated as well.
$(IFS=,; echo "${array[*]:i:4}") joins the array with commas to be
fed to java as an argument.
If the output looks good, drop echo in front of java.
[Edit]
As for the parallelism, we can make use of -P option to xargs.
Would you please try:
array=("USA+AL" "USA+AK" "USA+AZ" "USA+AR" "USA+AS" "USA+CA" ...)
for (( i = 0; i < ${#array[#]}; i+=4 )); do
printf "%s\n" "$(IFS=,; echo "${array[*]:i:4}")"
done | xargs -P4 -L1 -I{} java -jar test-execute.jar --localities="{}"
It groups four states into an argument.
The -P4 option generates four processes at a time.
Then 16 states are processed in total at once.

Negative bound in Java

I'm making a program where I calculate a random number using a function named generarAleatorio.
public static int generarAleatorio(int l){
java.util.Random X = new java.util.Random();
return X.nextInt(l) ;
}
Then, I use that number to locate a value inside an array using the length of the array as the parameter for the generarAleatorio parameter
public static String generarFecha(){
int[] dias={1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30};
int[] mes={1,2,3,4,5,6,7,8,9,10,11,12};
return String.format("%d-%d",dias[generarAleatorio(dias.length)],
mes[generarAleatorio(generarAleatorio(mes.length))]);
}
The problem is that sometimes an Exception is showed that looks like this
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at generadorregistros.GeneradorRegistros.generarAleatorio(GeneradorRegistros.java:70)
at generadorregistros.GeneradorRegistros.generarFecha(GeneradorRegistros.java:108)
at generadorregistros.GeneradorRegistros.main(GeneradorRegistros.java:48)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
It tells me that the Bound im sending its not positive, but as far as I know, the length of the Array is always the same and also positive.
What's the cause of this? Is the length of the array not always positive?
Is the length of the array not always positive?
It is in your case. However, the problematic call doesn't use the array length but a random number:
generarAleatorio( generarAleatorio(mes.length) )
Here the inner generarAleatorio(mes.length) may return 0 in which case the outer generarAleatorio(0) fails.
How to fix the problem depends on what you want to do. Both of the following changes would make the error go away -- but the behavior of your program will be very different.
mes[generarAleatorio(generarAleatorio(mes.length)+1)]
mes[generarAleatorio(mes.length)]

How do I pass an arg to convert between numbers and strings

I am reading through the java tutorials, and I don't understand when it says
"The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:"
What I mean is how do I pass the values to the program. A piece of the code is this.
float a = (Float.valueOf(args[0])).floatValue();
float b = (Float.valueOf(args[1])).floatValue();
I have tried changing "args[0]" to "4.5" and "args[1]" to "87.2" which are the given values from this page.
https://docs.oracle.com/javase/tutorial/java/data/converting.html
Upon doing so I receive "requires two command-line arguments." which is the else part of the code. I'm pretty sure I am being oblivious to this. I have tried looking for anything regarding passing arguments but i can't find exactly what to do.
I have also tried creating two "string" values named one and two with the same values as above and inputting the string name into the args positions but still received the same outcome.
Is it something simple such as requesting an input from the user or should I manually put the values in there and if I need to add the values into the argument then how would I go about doing so.
The arguments passed to the main methods are the one typed when starting your java application from command line. An revelant example for your case would be :
java YourProgram 4.5 87.2
Then you will be able to access them from args[0] and args[1] as explained in the tutorial.
For more examples read the Command-Line arguments part of the java tutorial.
If you're running the program from a command line (typing something like java ValueOfDemo into a terminal), you would type java ValueOfDemo 4.5 87.2 to pass 4.5 and 87.2 as the first and second arguments, respectively. If you're running the program using an IDE such as Eclipse or NetBeans, search for that program's documentation on how to pass command line arguments to the program.
In general, command line arguments are arguments that are passed to the program you're running when the program is started. You can also ask the user for input while your program is running, but you would explicitly write code to do so and accept the value.
See this page for more information: https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
Open cmd(window key + r) and compile by command: javac yourClass.java and then execute by command: java yourClass 4.5 87.2 you will see result

Input In Java- How does it work?

Hey guys, with a lot of help from you i was managed to write this nice code (I'm new in it, so kind of exciting.. :) )
And still I have not understand how can I input this code.
first of all, I get an this error in the console line (I'm using Eclipse):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at NumberConverter.main(NumberConverter.java:5).
What does that mean?
I just want to chack whether it works, and I can't call the function/program any how.
I used to call in an "old fashion way", like in scheme, to the function that I wrote and see if something happens. How does it work in java? Do we call the program itself? function? what and where do we write? -I want to chack if it works, doesn't matter how, and I'll be glad to know how can I plugin input.
Thank you so much!
public class NumberConverter{
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
toOctal(i);
toHex(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
public static void toOctal(int int1){
System.out.println(int1 + " in octal is");
System.out.println(Integer.toOctalString(int1));
}
public static void toHex(int int1){
System.out.println(int1 + " in hex is");
System.out.println(Integer.toHexString(int1));
}
}
It means there was an ArrayIndexOutOfBoundsException at line 5 of NumberConverter. This is most likely going to be this line (if the full source contains a package statement followed by a blank line, this will be line 5):
int i = Integer.parseInt(args[0]);
Which tries to access the first argument you passes to the program, since you did not pass any arguments to the program the arbs array is empty and attempts to access args[0] results in ArrayIndexOutOfBoundsException.
If you were running this from the command line you it should look something like this:
$ java com.mypackage.NumberConverter 1
Here $ is the prompt, com.mypackage is presumed to be the package name and 1 is the command line argument which you will be able to access via args[0]`.
Since you are using eclipse and not via a command line here is a nice blog post on adding command line arguments from within eclipse.
you have to set arguments for app start up. You can do this in Run Configuration editor (Right click on project -> Run as.. -> Run Configurations). In Arguments tab you can put one to program Arguments field. One argument per line (eg. 5).
The ArrayIndexOutOfBoundsException occurs because of empty args array that you want to take first element of empty array - args[0]. You can't do this because the array is empty if no app start up arguments are set.
ArrayIndexOutOfBoundsExceptions means (from JavaDoc):
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.
From your exception, args[0] throws ArrayIndexOutOfBoundsExceptions because 0 is greater than or equal to args.length. My suggestion is to find out what arguments is the OS returning to your JVM which is then passed to your app and see if args[0] is initialized and populated.
Also, running a program from Eclipse requires you to set arguments through Run Configurations.
an ArrayIndexOutOfBoundsException is thrown when you try to access an index outside of an array. Let's say that I have an array of size 2. I can access the first and second elements using the indices 0 and 1 respectively, but if I try to access the element in index 4, an exception is thrown:
public static void stam() {
int[] array = { 0, 1 };
// this will print 0
System.out.println(array[0]);
// this will print 1
System.out.println(array[1]);
// this will crash the program
System.out.println(array[4]);
}
Your instinct was correct that you can easily test your program using input, although using a literal value and a variable are probably an easier, and certainly more flexible option. In any case, you can set up the run configuration to include command line arguments via the Run > Run Configurations... window.
As you probably guessed, the reason why your program was crashing is because you try to access the first command line argument in line 5 of your class, but the argument wasn't there, so the array has 0 elements.
A slightly more flexible way of running a java program with command line arguments is by calling the main method of a different class, and manually passing it a String array. But if you want to test your methods quickly, just pass them literal values.

String conversion in java is throwing array index out of range exception

I have written following code but it is throwing array index out of range exception
String options = "" + args[0];
if (options.toLowerCase().contains("failover"))
{
dataToPass[0]= "failover";
callScript("Clus1toNfastfastsamehost",dataToPass);
}
Exceptions:
exception_name = java.lang.ArrayIndexOutOfBoundsException
exception_message = Array index out of range: 1
Well, Either you are not allocated enough memory the dataToPass[] or you have not pass arguments to the program. If no arguments is passed then args, it's a zero length array. Debugging will be a good option for you mate.
You are not passing an argument to your program.
Well, it's a straightforward exception. Check all your array lengths. How many items are in args? In dataToPass? Consider using a debugger.
UPDATE WITH CODE FIX
String options = ""
if (args.length > 0)
options += args[0]
Original comments:
There are two places you reference an array in the example code. args[0] and dataToPass[0]
It must be one of those two. So, a) you are not passing any arguments to the programs and args[0] is not defined -- this seems strange to me because I thought args[0] was the program name or b) dataToPass[0] was not allocated -- is dataToPass a zero length array and not a 1 length array?

Categories

Resources