-1

I am trying to write a method that finds the smallest out of three numbers. I think something is wrong with the "else if" statement in my code here. It keeps telling me that "variable d may not have been initialized." but I did initialize it. Maybe I wrote the "else if" statement wrong.

public class Solution {
    public static int min(int a, int b, int c) {
        int d;
        if ((a <= b) && (b <= c))
            d = a;
        else if ((a >= b) && (b >= c))
            d = c;

        return d;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(min(1, 2, 3));
        System.out.println(min(-1, -2, -3));
        System.out.println(min(3, 5, 3));
        System.out.println(min(5, 5, 10));
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Vince
  • 1

4 Answers4

1

Try this

int d = a;
if (d > b) {
  d = b;
} 
if (d > c) {
  d = c;
}
return d;

The error happened because
int d; declares it and not initialize it.

Mangaldeep Pannu
  • 3,738
  • 2
  • 26
  • 45
0

You need to make sure int d is assigned a value before the return statement. Your logic is also wrong and you have missed else statement in your code. You can try the code below:

  public static int min(int a, int b, int c) {

  int d ;
  if ((a <= b) && (a <= c))
      {
      d = a;
      }  
  else if ((a >= b) && (b <= c))
      {
      d = b;
      }
  else
      {
      d=c;
      }

  return d;
}
sp324
  • 285
  • 2
  • 20
-1

Either initialize int d with a value, and/or include an else statement to assign d encase the return statement throws a null. You should always plan for what happens when your if and if else statements are evaluated as false.

barbsan
  • 3,418
  • 11
  • 21
  • 28
-6

Use int d=0;

to intilize d with NULL

Remember: When using elseif{} you must have to endup with else{}

if(condition){

}else if(condition){

}
else{
}