How to check if string.split () returns null

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 am using string.split () for every line I read from this file, for example:

String args[]         = line.split("\\|");                  
String candidatArgs[] = args[0].split(";");

if (args[1] != "" || args[1] != null) { 

    String inscrieriString[] = args[1].split(";");

      

Thing: when I reach Another Name;3|

after .split("\\|")

, the second part ( args[1]

) should be empty, either null

or ""

(I really don't know).

However, I get the error Array index out of bounds on if (args[1] != "" || args[1] != null)

(again, AT: Another Name;3|

)

+3


source to share


6 answers


The arguments will only have one element.



if (args.length> 1) {
    String inscrieriString [] = args [1] .split (";");
}
+7


source


You need to check the length of the array args

.

String.split()

returns an array of length 1 for your third line, so that's args[1]

out of bounds. You should also use String.isEmpty()

instead != ""

.



Chances are, you can even skip additional checks - checking the length of the array should be sufficient:

if (args.length > 1) {
    String inscrieriString[] = args[1].split(";");
    ...
}

      

+4


source


Check the length args

when splitting and only access the other index if the length allows it (if 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" }

      

+1


source


try it

String args[]         = line.split("\\|",2);                  
String candidatArgs[] = args[0].split(";");

if (args.length==2) 
    String inscrieriString[] = args[1].split(";");

      

+1


source


args[1]

is not empty or null. It is outside the array.

System.out.println("Another Name;3|".split("\\|").length);

      

You will need to check the length of the array before using it.

+1


source


I think you can check the length of the arguments and it should return 1 or 2. If it's 1, you know there are no arguments [1].

+1


source







All Articles