Home > Mobile >  return statements are not coming out right
return statements are not coming out right

Time:11-18

I need to code a method that checks if:

A = all numbers are equal. B = no numbers are equal. C = at least two numbers are equal.

Im just beginning to learn all this in uni but I cant seem to figure out what i am doing wrong in this method which needs to return the given conditions e.g("A", "B", "C").

public static int checkNumbers(int x, int y, int z) 
{ 
    int A,B,C;

    A = 'A';
    B = 'B';
    C = 'C';

    if((x == y) && (y == z))
    {
        return A;
    }
    else if ((x == y) || (x == z) || (y == z))
    {
        return C;

    }
    else
    {
        return B;
    }
}

CodePudding user response:

You have declared A, B and C as integers and then assigned to them a 'Char'. Maybe try

public static char checkNumbers(int x, int y, int z) 
{ 
    char A,B,C;

    A = 'A';
    B = 'B';
    C = 'C';

    if((x == y) && (y == z))
    {
        return A;
    }
    else if ((x == y) || (x == z) || (y == z))
    {
        return C;

    }
    else
    {
        return B;
    }
}

Alternatively, use a String

public static String checkNumbers(int x, int y, int z) 
{ 
    String A,B,C;

    A = "A";
    B = "B";
    C = "C";

    if((x == y) && (y == z))
    {
        return A;
    }
    else if ((x == y) || (x == z) || (y == z))
    {
        return C;

    }
    else
    {
        return B;
    }
}

CodePudding user response:

return the given conditions e.g("A", "B", "C")

Then you should return a String (or char), not int.

public static String checkNumbers(int x, int y, int z) { 
    if (x == y && y == z) {
        return "A";
    } else if (x == y || x == z || y == z) {
        return "C";
    } else {
        return "B";
    }
}

public static void main(String[] args) {
   System.out.println(checkNumbers(0, 0, 0)); // A 
   System.out.println(checkNumbers(0, 0, 1)); // C
   System.out.println(checkNumbers(0, 1, 2)); // B
}

Otherwise, you need to print (char) checkNumbers(...) to cast the int return value into a printable character

  • Related