mercredi 23 janvier 2019

How do I write a proper else if statement?

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) {
    //write your code here
   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));
}

}

Aucun commentaire:

Enregistrer un commentaire