我一直在研究Java。我有这个问题,我试图调试好几天但无济于事。
如何将成绩[0]引用到lab.score(60),以便我可以在toString
方法中使用它?我正在尝试将分数编号分配给实验室并对成绩[0]进行引用,以便我可以在主程序中使用它,如下面的代码所示,但我得到的只是这个错误:
Exception in thread "main" java.lang.NullPointerException
at CourseGrades.toString(CourseGrades.java:35)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at CourseGrades.main(CourseGrades.java:58)
我的代码:
import java.util.Scanner;
public class CourseGrades {
private GradedActivity grades[] = new GradedActivity[3];
public void setLab(GradedActivity lab)
{
lab = new GradedActivity();
lab.setScore(60);
grades[0] = lab;
}
public void setPassFailExam(PassFailExam passfailexam)
{
passfailexam = new PassFailExam(10,6,70);
grades[1] = passfailexam;
}
public void setEssay(Essay essay)
{
essay = new Essay(80);
grades[2]= essay;
}
public void setFinalExam(FinalExam finalexam)
{
finalexam = new FinalExam(50,4);
grades[3] = finalexam;
}
public String toString()
{
String str = "Lab Score: " + grades[0].getScore() +
"\tGrade: " +
"\nPass/Fail Exam Score: " +
"\tGrade: " +
"\nEssay Score: " +
"\tGrade: " +
"\nFinal Exam Score: " +
"\tGrade: " ;
return str;
}
public static void main(String[] args)
{
CourseGrades kk = new CourseGrades();
String st = kk + "testing";
System.out.println(st);
}
public class GradedActivity
{
private double score;
public void setScore(double s)
{
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >=90)
letterGrade ='A';
else if (score>=80)
letterGrade ='B';
else if (score >=70)
letterGrade ='C';
else if (score >=60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}