I am reading data from a file:
Some Name;1|IN03PLF;IN02SDI;IN03MAP;IN02SDA;IN01ARC
Some Other Name;2|IN01ALG;IN01ANZ
Another Name;3|
Test Testson;4|IN03MAP;IN01ARC;IN01ALG
I use string.split() for every line I read from that file, like this:
String args[] = line.split("\\|");
String candidatArgs[] = args[0].split(";");
if (args[1] != "" || args[1] != null) {
String inscrieriString[] = args[1].split(";");
Thing is: when I reach Another Name;3|
after .split("\\|")
the second part (args[1]
) should be empty, either null
or ""
(I don't really know).
However I get an Array index out of bounds error on if (args[1] != "" || args[1] != null)
(again, at: Another Name;3|
)
split(CharSequence input, int limit) . The return value comes from a non-null ArrayList on which toArray is called. toArray does not return null: in the event of an empty list you'll get an empty array back. So in the end, no, you don't have to check for null.
The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
We can simply compare the string with Null using == relational operator. Print true if the above condition is true. Else print false.
The args will only have one element in it.
if (args.length > 1) { String inscrieriString[] = args[1].split(";"); }
You need to check the length of your args
array.
String.split()
returns an array of length 1 for your third line, so that args[1]
is out of bounds.
You should also use String.isEmpty()
instead of != ""
.
Most likely, you can even skip your additional checks - checking the array length should be sufficient:
if (args.length > 1) {
String inscrieriString[] = args[1].split(";");
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With