Mohammad Fadin
Mohammad Fadin

Reputation: 579

Reading data from a file problem (Java Beginner Language)

I'm having a problem reading the data from a file.

When I try to calculate the GPA after inputting from the file I only get the name and the ID right. check the full code 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)

`

I really need help with this. It took me hours to fix it but I could not.

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();
            }
            }
    }

The input data is like this:

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+

This is the method calculating the GPA,etc it works fine with manual input.

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("");
}

Upvotes: 0

Views: 189

Answers (1)

Howard
Howard

Reputation: 39177

You have to initialize your "sub"arrays correctly, i.e. inside your i-loop but right before the j-loop add the following lines:

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

Upvotes: 1

Related Questions