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?
Related
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)]
Provided a String, my objective is to check if I can make that String a palindrome string even after re-arranging the characters.
For eg: aaabbbb can be made palindrome by changing to : bbaaabb
So what I did try is to compare all the permutations of the string with its reverse, if it exists, print a YES! . And here is the code so far:
private static void permutation(String prefix, String str)
{
temp.setLength(0); //temp is a StringBuilder
int n = str.length();
if((n==0) && (str.charAt(0)==str.charAt(n-1)))
{
temp.append(prefix);
temp.reverse();
if(prefix.equals(temp.toString()))
{
System.out.println("YES");
System.exit(0);
}
}
else
{
for(int i=0;i<n;i++)
permutation(prefix+str.charAt(i),str.substring(0,i)+str.substring(i+1,n));
}
}
Now the problem is, at runtime I get a java.lang.StringIndexOutOfBoundsException at this line: permutation(prefix+str.charAt(i),str.substring(0,i)+str.substring(i+1,n));
What might be possibly causing this?
This line will give you the exception too:
if((n==0) && (str.charAt(0)==str.charAt(n-1)))
If n==0 then the string is empty, and charAt(0) will fail. Not sure what you're testing here.
I'm not going to debug this for you, but I will suggest a process for how to debug this kind of thing yourself.
Identify the problem. All of the detail about the palindromes is irrelevant. The problem is a java.lang.StringIndexOutOfBoundsException when calling one of the methods on the String.
Narrow in on exactly what's failing. There are several method calls in the line that is failing. If it's not obvious which method call is the problem, either single-step through it with a debugger or break that line into several lines, e.g. by creating intermediate variables to hold intermediate state.
Reproduce the problem in a simplified example. Create a new class with a main() method or write a unit test and write code that shows the problem. Remove everything that isn't absolutely essential to show the problem.
Fix your example. Once you've isolated the problem and read the documentation, it will probably be obvious how to fix it. If it's not, and you're still stuck, post the simple example on Stack Overflow and explain what you are expecting and what you're getting.
Fix your code. Apply the same fix to your original code.
String index out of bound exception -This exception is thrown by the methods of the String class, in order to indicate that an index is either negative, or greater than the size of the string itself.
In above code you are calling permutation() method recursively .
Let's say we passed String str="xy" and prefix as "" to permutation() method first time.
As its length is more than 0 it will come to the else block.
In else block we are looping str with its length.
Here length i.e n is 2.
In first loop, i=0. So prefix + str.charAt(i) will give "" + "x" = "x" and str.substring(0,i)+str.substring(i+1,n)
will give str.substring(0,0)+str.substring(0+1,2)=""+"y"="y".
Now again we are passing these values to permutation() method; i.e. permutation("x","y").
So the time when you passed these value in method, at that time instantly string str became "y" and string prefix became "x"
but still you are in loop, and in second loop i=1 and prefix+str.charAt(1) i.e. "x"+"y".charAt(1) will throw exception.
Here you can see string str="y", length is 1 and we are trying to get char at position 1. This is why you got this exception.
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 :)
This question already has answers here:
Why is "out of range" not thrown for 'substring(startIndex, endIndex)'
(6 answers)
Closed 4 years ago.
I apologize if title is not clear.
Now, in strings index starts at 0. So for instance:
Index 0 1 2 3 4
String H E L L O
In this case, the last index is 4.
If I would try to do something like this:
System.out.println("hello".charAt(5));
It would throw an 'Index Out Of Bounds Exception', as it should.
However, if I try to run the following code:
System.out.println("hello".substring(5));
It does run! I wrote similar code, noticed this later and could not figure it out.
Eventually, the question is that how is this possible that we can reach this index we should not? It allows us to write:
stringObj.substring(stringObj.length());
and it doesn't look very safe as stringObj.length() return us an integer that is one more than what the last index is.
Is it made intentionally and does this have a purpose? If so, what is this purpose and what is the benefit it brings?
It is easier to work with substring when you think of indexes like this (like letters are between indexes)
H E L L O
0 1 2 3 4 5 <- acceptable range of indexes for "HELLO"
^ ^
| |
start end = length
(min index) (max index)
When you substring from start to end you get only characters between these indexes.
So in case of "HELLO".substring(2,4) you will get part
L L
2 3 4
which returns "LL".
Now in case of substring(5) it acts same as substring(5,length) which means in this case it is substring(5,5). So since 5 index exists in our "model" as acceptable value, and since there are no characters between 5 and 5 we are getting empty string as result.
Similar situation happens in case of substring(0,0) substring(1,1) and so on as long as indexes are acceptable by our model.
StringIndexOutOfBoundsException happens only when we try to access indexes which are not acceptable, which means:
negative ones: -1, -2, ...
greater than length. Here: 6 7, ...
It would not compile due to 'Index Out Of Bounds Exception',
It does compile. You get a runtime Exception when you try to execute the code.
System.out.println("hello".substring(5));
Eventually, the question is that how is this possible that we can reach this index we should not?
Read the API for the substring(...) method. It explains how the method works and what the parameter means.
In this case it returns an empty String.
Refer to the substring method at Java String API
(http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int))
A String ".length()" method will return the number of characters in the string.
if you count "HELLO" from 0->4, it will still amount to 5 characters (the length), which is the number returned when you call "Hello".length().
If you want to access the last character of a String, use (Stringobj.length()-1); Accessing the last element of a String or Array through utilizing its .length() or .size() method calls is standardized across Java.
In this case details of implementation of methods charAt and substring are helpful to know.
charAt as described in this tutorial can be described as method that:
returns the character located at the String's specified index. The string indexes start from zero.
That is why calling:
System.out.println("hello".charAt(5));
gives
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 5
Because maximum index is, as you perfectly described, only 4.
substring is described in java documentation and explains your exact situation here in the "Examples" section which states that :
"emptiness".substring(9) returns "" (an empty string)
For additional reference, here is the source code for java's substring(int index) implementation, where you can see that it uses java's substring(int beginInndex, int endIndex) method.
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.