-1

I want the user to input n numbers of his wish and write a program in java to find the average using arrays. I came up with the following program, but there seems to be a problem when i run it: Exception in thread "main" java.lang.NullPointerException at wert.main(wert.java:12)

This is the code in question:

import java.util.Scanner;
public class wert {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int gucci[] = null; 
    System.out.print("Enter the length\n");
    int n = sc.nextInt();
    System.out.println("enter the numbers : ");
    for(int i=0;i<n;i++){

        int k = sc.nextInt();
        gucci[i] = k;
        }
    int m = average(gucci);
    System.out.println(m/n);

}
    public static int average(int x[]){
        int total = 0;
        for(int f: x){
            total =+ f;
        }
        return total;
    }   
}

I'm sorry if I am asking a really basic question. I started learning java on my own a few days back.

F. Stephen Q
  • 4,208
  • 1
  • 19
  • 42
Bijesh K.S
  • 101
  • 5

1 Answers1

3

This is the problem

int gucci[] = null;

Because the array is null the assignment fails With NullPointerException.

Change this part

int gucci[] = null;
System.out.print("Enter the length\n");
int n = sc.nextInt();

to

System.out.print("Enter the length\n");
int n = sc.nextInt();
int[] gucci = new int[n];

This will create an array of length you will enter.

Another problem is here

total =+ f;

If you want to add total = total+f it should be like below.

total += f;
Mritunjay
  • 25,338
  • 7
  • 55
  • 68