The args will only have one element in it.
if (args.length > 1) { String inscrieriString[] = args[1].split(";"); }
Question
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|
)
Solution
The args will only have one element in it.
if (args.length > 1) { String inscrieriString[] = args[1].split(";"); }
OTHER TIPS
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(";");
...
}
Check the length of args
when splitting and only access the other index if the length allows it (if the args.length > 1
).
In this case:
String line = "Another Name;3|"; //simplified for the example
line.split("\\|");
It will return this array:
{ "Another Name;3" }
try
String args[] = line.split("\\|",2);
String candidatArgs[] = args[0].split(";");
if (args.length==2)
String inscrieriString[] = args[1].split(";");
args[1]
isn't empty or null. It is out of bounds in the array.
System.out.println("Another Name;3|".split("\\|").length);
You would need to check the length of the array before using it.
I think you can test the length of args and it should return 1 or 2. If it's 1 you know that there's no args[1].