从文件问题中读取数据(Java初学者语言)

时间:2011-05-29 09:18:30

标签: java

伙计我在从文件中读取数据时遇到问题。

当我从文件输入后尝试计算GPA时,我只得到名称和ID。检查完整代码here

Name: Ali Ahmad
ID: 2009000

Exception in thread "main" java.lang.NullPointerException
    at IcsProject.display(IcsProject.java:136)
    at IcsProject.main(IcsProject.java:45)

`

我真的需要帮助。我花了几个小时修理它,但我不能。

public static void readFromFile() throws IOException
{
    System.out.println("Enter the file name ");
        String FileNameInput = keyboard.next();
        Scanner filein = new Scanner(new FileInputStream(FileNameInput));


        stuName = filein.nextLine();
        ID = filein.nextInt();

        filein.next();
        semNum = filein.nextInt();


    courseCode=new String[semNum][];
    creditHours=new int[semNum][];
    grade=new String[semNum][];
    semCode=new int[semNum];

    for(int i = 0; i < semNum; i++)
    {
            semCode[i] = filein.nextInt();

            filein.next();
            semCourses = filein.nextInt();

            for(int j = 0; j < semCourses; j++)
            {
              courseCode[i][j]=filein.next();
              creditHours[i][j]=filein.nextInt();
              grade[i][j]=filein.next();
            }
            }
    }

输入数据如下:

Ali Ahmad
2009000
Semesters 2

093
Courses 2

IAS100  2  A+
PE100   2  B

101
Courses 4

ICS103  3  A+
MATH101 4  B
PHYS101 4  C+
CHEM101 4  D+

这是计算GPA等的方法,它可以通过手动输入正常工作。

public static void display(PrintWriter output)
{
 output.println("Name: "+stuName);
 output.println("ID: "+ID);
 output.println("");

 GPA=new double[semNum];
 for(int i=0;i<semNum;i++)
 {
 GPA[i]=0.0;
 double creditHoursSum=0.0;
 for(int j=0;j<courseCode[i].length;j++)
 {
  GPA[i]+=creditHours[i][j]*gradeValue(grade[i][j]);
  creditHoursSum+=creditHours[i][j];
 }
 GPA[i]=GPA[i]/creditHoursSum;
 }
 cumulativeGPA=0.0;
 for(int i=0;i<semNum;i++)
 cumulativeGPA+=GPA[i];
 cumulativeGPA=cumulativeGPA/semNum;
 for(int i=0 ; i < semNum ; i++)
 output.printf("GPA for semester %d  = %.2f\t%s\n",semCode[i],GPA[i],gpaLvl(GPA[i]));//Using `Printf` To limit the number of digits of the GPA. I learned the method from our Course Book.Took me a while to get it though.
 output.printf("\nCumulative GPA = %.2f\n",cumulativeGPA);
 output.println("");
}

1 个答案:

答案 0 :(得分:1)

您必须正确初始化“子”数组,即在i - 循环内,但在j - 循环之前添加以下行:

courseCode[i] = new String[semCourses];
creditHours[i] = new int[semCourses];
grade[i] = new String[semCourses];