为什么我的方法说它必须返回类型字符串并给我一个错误,即使我的方法确实返回了类型字符串

时间:2019-03-23 12:18:07

标签: java

 
   public static String grade(){
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter your letter grade");
    String grade = s.next();
    String a = "Your grade is between 93.0 and 100";
    String b = "Your grade is between 83.0 and 93.0";
    String c = "Your grade is between 73.0 and 83.0";
    String d = "Your grade is between 63.0 and 73.0";
    String f = "Your grade is less than 63.0";
    if(grade.equals('A')){
        return a;
    }else if (grade.equals('B')){
        return b;
    }else if (grade.equals('C')){
        return c;
    }else if (grade.equals('D')){
                return d;
    }else if (grade.equals('F')){
        return f;
    }
}

2 个答案:

答案 0 :(得分:1)

您的方法中的问题是它缺少默认的返回类型。如果输入的值不是A-F,则您的方法不会返回字符串。

因此抛出异常或返回默认值(例如null

if (grade.equals("A")) {
    return a;
} else if (grade.equals("B")) {
    return b;
} else if (grade.equals("C")) {
    return c;
} else if (grade.equals("D")) {
    return d;
} else if (grade.equals("F")) {
    return f;
}
throw new IllegalArgumentException("The value you entered is not valid");

除了将Stringchar做比较外,您不应该这样做,因为那是不同的类型。因此,请使用"而不是',就像我在上面的代码段中所示。

最后,您还可以使用switch代替所有的else if语句:

switch (grade) {
    case "A":
        return a;
    case "B":
        return b;
    case "C":
        return c;
    case "D":
        return d;
    case "F":
        return f;
}
return "some default";

答案 1 :(得分:1)

您必须为该方法返回null,空(“”)或默认字符串。因为,嵌套if条件就像一个单独的函数,并且这些条件的返回值是该if or else if条件的局部变量(仅在条件内部有效)。通过以下方式更正您的代码。

public static String grade() {

    Scanner s = new Scanner([System.in](https://System.in));

    System.out.println("Please enter your letter grade");

    String grade = [s.next](https://s.next)();

    String a = "Your grade is between 93.0 and 100";

    String b = "Your grade is between 83.0 and 93.0";

    String c = "Your grade is between 73.0 and 83.0";

    String d = "Your grade is between 63.0 and 73.0";

    String f = "Your grade is less than 63.0";



    if(grade.equals('A')) {

        return a;

    } else if (grade.equals('B')) {

        return b;

    } else if (grade.equals('C')) {

        return c;

    } else if (grade.equals('D')) {

         return d;

    } else if (grade.equals('F')) {

        return f;

    }

    return null; // or return f;
}