0

I have a problem with method which should use a code, search the table for the code, and then return me data with that code index; This is what I use now. The Eclipse is telling me that result may not be initialised. But I don't see another way to do this.

public String getService(String serviceCode){
    String result;
    for(int i=0;i<data.length;i++){
        for(int j=0;j<3;j++){
            if(serviceCode==data[i][j]){
                result =  data[i][j+1].toString() + data[i][j+2].toString();
            }
        }
    }
    return result;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3208593
  • 1
  • 1
  • 2
  • `serviceCode==data[i][j]` [:_(](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) Click on the crying face. – Maroun Jan 26 '14 at 13:44
  • What happens if `data.length` is `0`? you would never enter the loop and your result would remain `null`! Same case if the program doesn't enter the following loops. So either use `String result = new String();` or simply `String result = ""`. – Yan Foto Jan 26 '14 at 13:45

3 Answers3

2

The Eclipse is telling me that result may not be initialised

That's true:

public String getService(String serviceCode){
    String result; // <--
    for(int i=0;i<data.length;i++){
        for(int j=0;j<3;j++){
            if(serviceCode==data[i][j]){
                result =  data[i][j+1].toString() + data[i][j+2].toString();
            }
        }
    }
    return result;
}

If your loops don't get executed, then result will be not initialized.

Change it to

String result = null;

As a side note, you shouldn't use == to compare strings, you should use .equals:

 if(serviceCode.equals(data[i][j]))
BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • Even if the loop gets executed `result` will be `null`. He's comparing references with `==` (Which probably will be always `false`). – Maroun Jan 26 '14 at 13:46
  • @ᴍarounᴍaroun Yes, but he's asking why he gets "result may not be initialised", and that's why. And I added a note about string comparison – BackSlash Jan 26 '14 at 13:46
1

You are using == on strings, which compares references, not actual equality. Always use string.equals(otherstring) instead.

As for your problem, String result; is never initialised to null. If you declared it as a field, it would automatically have been assigned the value null, but inside the scope of a method it is undetermined. The data is whatever junk bytes happened to still be there.

So do String result = null;.

Reinstate Monica
  • 2,767
  • 3
  • 31
  • 40
0

The problem is that if data.length is equal to 0 then you won't get any result - you have to think functionally what your method should do in such situation - maybe IllegalStateException will work for you?

Jakub Kubrynski
  • 13,724
  • 6
  • 60
  • 85