简体   繁体   中英

return statements are not coming out right

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 eg("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;
    }
}

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;
    }
}

return the given conditions eg("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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM