不确定为什么我的程序默认输出最后一个if语句

时间:2017-10-15 08:42:23

标签: java

程序旨在将输入作为整数并返回成绩和成绩点。默认情况下,它会一直输出最后一个if语句。任何帮助都表示赞赏,因为我是一个完整的初学者。

import java.util.Scanner;

public class gradePoint {
    int grade;
    String x;

public void getGrade() {
    int x = grade;

    if (x>90 && x<100) {
        System.out.println("A+ ; GradePoint 9");
    }else if(x>80 && x<89){
        System.out.println("A ; GradePoint 8");
    }else if(x>75 && x<79){
        System.out.println("B+ ; GradePoint 7");
        return;
    }else if (x>70 && x<74){
        System.out.println("B ; GradePoint 6");
    }else if (x>65 && x<69){
        System.out.println("C+ ; GradePoint 5");
    }else if (x>60 && x<64){
        System.out.println("C ; GradePoint 4");
    }else if (x>55 && x<59){
        System.out.println("D+ ; GradePoint 3");
    }else if (x>50 && x<54){
        System.out.println("D ; GradePoint 2");
    }else if (x>48 && x<49){
        System.out.println("E ; GradePoint 1");
    }else if (x<47){
        System.out.println("F ; GradePoint 0");
    }

}

public static void main (String[] args){
    System.out.println("enter grade");
    Scanner sc = new Scanner (System.in);

    int grade = sc.nextInt();

    gradePoint g = new gradePoint();
    g.getGrade();

}
}

输出:

 enter grade

   90

   F ; GradePoint 0

2 个答案:

答案 0 :(得分:1)

您永远不会将输入成绩传递到gradePoint对象。

因此,实例成员int grade;默认仍为0,因此在int x = grade;之后,x也为0.

您可以使用构造函数初始化grade变量:

public gradePoint (int grade)
{
    this.grade = grade;
}

gradePoint g = new gradePoint(grade);
g.getGrade();

或者您可以将成绩直接传递给getGrade()方法:

public void getGrade(int grade) {
    if (grade>90 && grade<100) {
        ...
}

gradePoint g = new gradePoint();
g.getGrade(grade);

答案 1 :(得分:0)

您的程序会一直打印F ; GradePoint 0,因为grade类的字段gradePoint为零。 grade内的变量main是本地的。它的价值是什么并不重要,因为grade内的getGrade不会改变。

您应该对程序进行一些更改以解决此问题:

  • 将类重命名为GradePoint以遵循Java命名准则,
  • getGrade重命名为printGrade,并将其设为static方法,
  • 授予printGrade grade int类型参数,
  • 从班级中删除字段grade
  • 将变量grademain传递到printGrade

修改后,main应如下所示:

public static void main (String[] args){
    System.out.println("enter grade");
    Scanner sc = new Scanner (System.in);
    int grade = sc.nextInt();
    printGrade(grade);
}