为什么我的方法不向 main 返回字符串或字符?

我正在尝试使用多种方法来完成一个简单的程序来计算测试的成绩,但我的方法不会返回任何字母。IDE 说我的方法必须返回类型为 的结果String。


public static String getGrade1(int num1) {

    if (num1 <= 100 && num1 >= 90) {

        String a = "A";

        return a;

    } else if (num1 < 90 && num1 >= 80) {

        String b = "B";

        return b;

    }else if (num1 < 80 && num1 >= 70) {

        String c = "C";

        return c;

    }else if (num1 < 70 && num1 >= 60) {

        String d = "D";

        return d;

    }else if (num1 < 60) {

        String f = "F";

        return f;

    }

}


凤凰求蛊
浏览 165回答 3
3回答

largeQ

要解决您的问题,最简单return的方法是在方法末尾添加一条 default语句,例如:public String method() {&nbsp; &nbsp; // Code&nbsp; &nbsp; return ""; // Return some default String value}笔记:如果您宁愿发生异常而不是返回默认值,您可以执行以下操作:public String method() throws Exception {&nbsp; &nbsp; // Code&nbsp; &nbsp; throw new Exception(); // Throw some exception}

郎朗坤

如果不是 void 类型,您的函数必须始终返回一个值。问题是,如果您调用getGrade1(110)您的函数,则不会到达 return 语句。else在最后添加一个子句(没有尾随if),它返回一些东西,它应该停止给你警告。此代码应该工作:public static String getGrade1(int num1) {&nbsp; &nbsp; if (num1 <= 100 && num1 >= 90) {&nbsp; &nbsp; &nbsp; &nbsp; return "A";&nbsp; &nbsp; } else if (num1 < 90 && num1 >= 80) {&nbsp; &nbsp; &nbsp; &nbsp; return "B";&nbsp; &nbsp; } else if (num1 < 80 && num1 >= 70) {&nbsp; &nbsp; &nbsp; &nbsp; return "C";&nbsp; &nbsp; } else if (num1 < 70 && num1 >= 60) {&nbsp; &nbsp; &nbsp; &nbsp; return "D";&nbsp; &nbsp; } else if (num1 < 60) {&nbsp; &nbsp; &nbsp; &nbsp; return "F";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return "";&nbsp; &nbsp; }}

暮色呼如

尝试这个:&nbsp;public static String getGrade1(int num1) {&nbsp; &nbsp; String grade = "";&nbsp; if (num1 <= 100 && num1 >= 90) {&nbsp; &nbsp; &nbsp; &nbsp; grade = "A";&nbsp; &nbsp; } else if (num1 < 90 && num1 >= 80) {&nbsp; &nbsp; &nbsp; &nbsp; grade = "B";&nbsp; &nbsp; }else if (num1 < 80 && num1 >= 70) {&nbsp; &nbsp; &nbsp; &nbsp; grade = "C";&nbsp; &nbsp; }else if (num1 < 70 && num1 >= 60) {&nbsp; &nbsp; &nbsp; &nbsp; grade = "D";&nbsp; &nbsp; }else if (num1 < 60) {&nbsp; &nbsp; &nbsp; &nbsp; grade = "F";&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; grade = "NA";&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;return grade;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java