0

Java code asks the user to enter the number of grades he want to enter then it enter a function or method to put them into array then enter another method to find average.

the code compile without error but when i run and i put the number of grades but the function grades crash, I am used to code in c++ so i may be missing some basics of java. Your understanding will be appreciated. I hope when fixing it , to tell me what is my mistake.

package lab10ex8;

import java.util.Scanner;

public class Lab10ex8 {
    

    
    public static double[] grades ( int n, double a [] ) {
        Scanner S = new Scanner(System.in);
        double grade=0;
        for(int i=0; i<n ; i++)
        {
            grade = S.nextDouble();
            a[i] = grade;
            
        }
        return a;
    }
    
    public static double average( double a[] ) {
        double average=0;
        double c;
        double sum=0;
        Scanner S = new Scanner(System.in);
        
        for(int i=0; i< a.length ; i++){
            
            c= a[i];
            sum = sum+c;
        }
        average = sum/a.length;
        return average;
    }

    public static void main(String[] args) {
        int n;
        System.out.println( "Enter the number of Grades : " );
        Scanner S = new Scanner(System.in);     
        n=S.nextInt();
        double a[] = null;
        grades(n,a);
        average(a);
        
        
    }
    
}
joe souaid
  • 40
  • 6
  • You initialize `a` to null in the `main()` method. You probably want it to be `double[n]`, no? – vsfDawg May 07 '21 at 18:01
  • 1
    What do you mean by "crash"? What error are you getting? – Mureinik May 07 '21 at 18:01
  • @Mureinik the error is:Exception in thread "main" java.lang.NullPointerException at lab10ex8.Lab10ex8.grades(Lab10ex8.java:16) at lab10ex8.Lab10ex8.main(Lab10ex8.java:43) – joe souaid May 07 '21 at 18:06

2 Answers2

1

You need to provide memory to the array a. Like this:

double a[] = new double[n];
rahul_vyas
  • 40
  • 6
1

You must initialize you double array a to double a[] = new double[n]:

public static void main(String[] args) {
    int n;
    System.out.println( "Enter the number of Grades : " );
    Scanner S = new Scanner(System.in);     
    n=S.nextInt();
    **double a[] = null;** => double a[] = new double[n];
    grades(n,a);
    average(a);
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Rohit Maurya
  • 154
  • 1
  • 1
  • 10