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; } }
答案 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");
除了将String
与char
做比较外,您不应该这样做,因为那是不同的类型。因此,请使用"
而不是'
,就像我在上面的代码段中所示。
最后,您还可以使用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;
}