Search code examples
javanullnotnull

Result not null in my code, if "sorIndex" is invalid


I would need some guidance from You, at the moment I have this challenge with this exercise:

The aim of this code would be, to split a String(szoveg) to rows and give back the result row(sorIndex) as a result, if sorIndex is in the range of the String Array(String szoveg is splitted into this array).

If the requested number of the row is not in the valid range(0-length of the array) it should give back a null value. The IDE for testing the excercise returns a mistake, which is the following(Hungarian + English):

"A getSor() metódus nem működik jól. Nem létező sorIndexet megadva null-t kell visszaadjon a metódus. A konstruktor paramétere:"

"The getSor() method is not working properly. Given a not valid sorIndex, the method should return null. The parameter of the constructor:" -there is nothing after this part in the IDE.

 public String getSor(int sorIndex) {

        int sorok= szoveg.split("\n").length;

        String sor;

        if (sorIndex >= 0 && sorIndex <= sorok) {  

            String[] stringTomb = new String[sorok];

            stringTomb = szoveg.split("\n");

            sor = stringTomb[sorIndex];

        } else {

            sor = null;

      }

        return sor;

    }

Does anyone have any idea where did I made the mistake?

Thank you!


Solution

  • The error message tells you that if an invalid sorIndex is passed, then a null should be returned. This means that instead of getting into the else branch in your logic, it goes into the if in an invalid manner.

    The reason of this is that arrays are 0-indexed, so you should compare against rows (sorok) in a srict manner:

    if (sorIndex >= 0 && sorIndex < sorok) { 
    

    That should fix the issue. However, your code computes split several times and is superfluous. I would refactor it to:

    public String getSor(int sorIndex) {
        if (szoveg == null) return null; // Handling the case when szöveg is not properly initialized
        String stringTomb[] = szoveg.split("\n");
        return ((sorIndex >= 0) && (sorIndex < szoveg.length)) ? stringTomb[sorIndex] : null;
    }
    

    I used the ternary operator to make this more readable, concise and short.