这是为了家庭作业。我已经完成了 90% 的工作,但是 NPE 导致我的程序每次都失败。我尝试了几种方法并阅读了非常详细的说明,这些说明在他希望程序结构方面非常详细,但我仍然无法弄清楚为什么即使在传递数据时它也会给出这个异常。我最初认为这是因为初始测试中没有通过数据。
运行程序的第一个 .java 文件:
class TestGPA
{
public static void main(String[] args)
{
if (args.length == 0)
{
System.out.println("Please supply grades to find GPA");
System.exit(0);
}
GPA gpa = new GPA(args);
else
{
GPA gpa = new GPA(args);
gpa.displayResult();
}
}
}
很多方法所在的第二个 .java 文件:
class GPA
{
String[] courseIdGrades;
String[] courseIds;
char[] grades;
double gpa;
String errorMsg;
GPA(String[] courseIdGrades)
{
String[] courseIds = new String[courseIdGrades.length];
char[] grades = new char[courseIdGrades.length];
processData();
}
void parseInput()
{
int i = 0;
while( i < courseIdGrades.length )
{
GPAUtil.validateCourseIdGrade(courseIdGrades[i]);
if(errorMsg != "NO_ERROR")
{
break;
}
else
{
courseIds[i] = courseIdGrades[i].substring(0,5).toUpperCase();
grades[i] = Character.toUpperCase(courseIdGrades[i].charAt(5));
i++;
}
}
}
double computeGPA()
{
int sum = 0;
for (int i = 0; i < grades.length; i++)
{
sum += GPAUtil.gradePoints(grades[i]);
}
double gpa = (double) sum / grades.length;
return gpa;
}
void processData()
{
parseInput();
if(errorMsg == "NO_ERROR")
{
computeGPA();
}
else
{
System.out.println("Input error - details are: " + errorMsg);
System.exit(0);
}
}
void displayResult()
{
System.out.println("--------------------");
System.out.println(" Course ID Grade" );
System.out.println("--------------------");
for (int i = 0; i < courseIds.length; i++)
{
System.out.println(" " + courseIds[i] + " " + grades[i]);
}
System.out.println("--------------------");
System.out.println(" GPA = " + gpa);
System.out.println("--------------------");
}
}
第三个 .java 是一个实用程序类:
public class GPAUtil
{
public static String[] validDepts = {"CS","EE","ME"};
public static String validateCourseIdGrade(String courseIdGrade)
{
String errorMsg = "NO_ERROR";
if (courseIdGrade.length() != 6)
{
errorMsg = "Course ID/Grade string invalid, must be 6 char.";
}
else
{
for(int i = 0; i < 3; i++)
{
if(courseIdGrade.substring(0,2).equalsIgnoreCase(validDepts[i]))
{
errorMsg = "NO_ERROR";
break;
}
else
{
errorMsg = "Dept ID invalid, must be one of: CS, EE, ME";
}
}
}
return errorMsg;
}
static int gradePoints(char grade)
{
int points = 0;
switch(grade)
{
case 'A':
points = 4;
break;
case 'B':
points = 3;
break;
case 'C':
points = 2;
break;
case 'D':
points = 1;
break;
default:
points = 0;
break;
}
return points;
}
}
例外:
Exception in thread "main" java.lang.NullPointerException
at GPA.parseInput(GPA.java:19)
at GPA.processData(GPA.java:48)
at GPA.<init>(GPA.java:13)
at TestGPA.main(TestGPA.java:5)
输入
根据错误消息,问题出现在 GPA 类中,这行:while( i < courseIdGrades.length )
这让我相信,通过不传递参数,它解析为 null,因此没有长度,所以我添加了对 null 的检查。但是,当我传递一个参数时,我仍然会收到相同的错误集。我不是在寻求答案,但朝着正确的方向轻推会非常有帮助。
我试过的
我尝试重组代码以阅读while(i < courseIdGrades[i].length())
无济于事,并且还硬编码了一个参数并开始传递它,但仍然得到相同的处理。应该发生的是,如果传递了无效的参数,它应该显示:Input error - details are: + errorMsg
由errorMsg
位于GPAUtil
.