简体   繁体   中英

Why do I get a message that my array is empty even after initializing it?

This is a part of a project I'm working on, When I try to insert elements to the array geneIds I get this error:

java.lang.ArrayIndexOutOfBoundsException: 0

I have initialized the array a couple of lines before, so why I can't insert elements to it?

else if (line.startsWith("!dataset_table_begin")) {
    line = bufferedReader.readLine();
    String[] array = line.split("\t");
    dataset.sampleIds = Arrays.copyOfRange(array, 2, array.length);
    dataset.geneIds = new String[(dataset.genesNumber)];
    dataset.geneSymbols = new String[(dataset.genesNumber)];
    dataset.dataMatrix = new float[dataset.genesNumber][dataset.samplesNumber];
    int count = 0;
    while ((line = bufferedReader.readLine()) != "!dataset_table_end") {
        String[] arry = line.split("\t");
        System.out.println(arry[0]);
        dataset.geneIds[count] = arry[0];
        dataset.geneSymbols[count] = arry[1];
        for (int i = 2; i < dataset.samplesNumber; i++) {
            dataset.dataMatrix[count][i] = Float.parseFloat(arry[i]);
        }
        count++;
    }
}

You have initialized the array from the results of split .

If the only character in the line is a tab character, you'll get an empty array as a result.

Before using any element in the array you should check its length.

Alternatively, you could use line.split( "\\t", 2 ) . This will return two elements in the array even though they are both empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM