string.split("\n")[1]
always gives me a ArrayIndexOutOfBoundsException
. Is there a way to prevent that? Does a real code like the following exist?
if(!ArrayIndexOutOfBoundsException)
string.split("\n")[1]
string.split("\n")[1]
always gives me a ArrayIndexOutOfBoundsException
. Is there a way to prevent that? Does a real code like the following exist?
if(!ArrayIndexOutOfBoundsException)
string.split("\n")[1]
string.split("\n")
returns a String
array.
string.split("\n")[1]
assumes that the return value is an array that has at least two elements.
ArrayIndexOutOfBoundsException
indicates that the array has less than two elements.
If you want to prevent getting that exception, you need check the length of the array. Something like...
String[] parts = string.split("\n");
if (parts.length > 1) {
System.out.println(parts[1]);
}
else {
System.out.println("Less than 2 elements.");
}
The first element of an array is at index 0. Do not assume that there are always two elements. The last index in an array has an index of (length - 1).
Indexing starts with 0, so by indexing with 1 you are trying to get the second element of the array which is in your case a potentiel second line of a text. You are having such error because you may have no line break in your string, to avoid such exception you can either use a try catch block (I don't like this method in your case) or just check if there is a line break in your string, you can do it like this:
if(yourString.contains("\n")){
//split your string and do the work
}
or even by checking the length of the parts due to split:
String[] parts = yourString.split("\n");
if(parts.length>=2){
//do the work
}
If you want to use the try-catch block:
try {
String thisPart = yourString.split("\n")[1];
}
catch(ArrayIndexOutOfBoundsException e) {
// Handle the ArrayIndexOutOfBoundsException case
}
// continue your work
You can easily use try-catch to avoid getting this message:
try{
string.split("\n")[1];
}catch(ArrayIndexOutOfBoundsException e){
//here for example you can
//print an error message
}