I’m new to java and am trying to write a simple program that basicly asks for user input and then returns the average. I keep getting java.lang.NullPointerException when trying to add. Why is this? This is the code I have so far.
import java.io.*;
class Numbers {
public static void main(String[] args) {
System.out.println("Hello USER! This is TRON, state the number of NUMBERS you wish to enter and I will return the Average..."); // Display the string.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer loopnum = null;
Integer i = null;
Long num = null;
Long sum = null;
Long avg = null;
try {
loopnum = Integer.parseInt(br.readLine());
}
catch(IOException e){
System.out.println("Error!");
System.exit(1);
}
System.out.println("OK now enter your numbers.");
for (i=1;i<=loopnum; i++) {
try {
System.out.println("Enter number "+i+":");
num = Long.parseLong(br.readLine());
sum += num;
}
catch(IOException e){
System.out.println("Error!");
System.exit(1);
}
}
avg = sum / loopnum;
System.out.println("TRON here, Your average is: " + avg);
}
}
Initialize! Change declaration to
Long sum = 0Lat the beginning of your code. This line is problematic in your loop:it’s same as
sum = sum + num;Evaluation is done from the right to left and you see it tries to add variablenumwith anullvariable sum.