程序旨在将输入作为整数并返回成绩和成绩点。默认情况下,它会一直输出最后一个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
答案 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
grade
从main
传递到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);
}