0

here is my code. I am simply wanting to return the int value if it matches if not I don't want to return anything but it keeps giving me errors saying that I need to add a return statement to my code. I'm new to Java so I don't quite understand why it's not working.

Any help you can provide would be greatly appreciated,

public int faceIndex(String currentWheelFace) {
    for (int i = 0; i < wheelFaces.length; i++) {
        if (wheelFaces[i] == currentWheelFace) {
            return i;
        }
    }
}
MaxxD17
  • 57
  • 4

3 Answers3

0

Should be like this

You should have a return statement outside loops

public int faceIndex(String currentWheelFace) {
  int number;
    for (int i = 0; i < wheelFaces.length; i++) {
       if (wheelFaces[i] == currentWheelFace) {
          number = i;
          break;
       }
     }
  return number;
 }
Cyrille Con Morales
  • 918
  • 1
  • 6
  • 21
0

In your code, the return breaks out of the method as soon as the condition is satisfied.

But if it falls through by exhausting the for loop, then there is no return value provided. That will generate a compile error, needing a return value.

So, provide a default return value and then the calling code can check for validity. You would have to document the range of values of valid returns, but it seems that returning -1 could indicate the value is not found.

Alan
  • 716
  • 5
  • 15
0

The problem is that, if ur condition fails, the function will return nothing, then it will become a void function instead of int. Also your return statement is inside a loop, which means that ur function will return more than one value if WheelFaces[i] becomes equal to CurrentWheelFace more than once.... If u dont want ur function to do that then just add a break statement:

public int faceIndex(String currentWheelFace) {
    int W;
    for (int i = 0; i < wheelFaces.length; i++) {
        if (wheelFaces[i] == currentWheelFace) {
            W=i;
            break;
        }else{
            W=//some other default int value;
             break;
        return W;
        }
    }
}