简体   繁体   中英

java.lang.NullPointerException when adding two numbers

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 = 0L at the beginning of your code. This line is problematic in your loop:

sum += num; 

it's same as sum = sum + num; Evaluation is done from the right to left and you see it tries to add variable num with a null variable sum.

You should initialize your Long variables in 0L , not null . Even better, use the primitive type long instead of the wrapper type Long and int instead of Integer , you don't need to use wrapper objects here! Do this:

int loopnum = 0;
int i = 0;
long num = 0L;
long sum = 0L;
long avg = 0L;

The above will get rid of the NullPointerException and will avoid the unnecessary boxing/unboxing of values between primitive and object data types.

All the other answers fail to address why you're getting the null pointer exception. You are using the Long object instead of the long primitive. Thus anytime you use a direct arithmetic operation (such as + ), the compiler will unbox Long into long by invoking Long.longValue() . So sum += sum gets translated to:

sum = Long.valueOf(sum.longValue() + sum.longValue());

Since sum is null you'll end up with a null pointer exception. Most people avoid this by just using the primitve long .

initialize your sum variable with a non null value. 0L perhaps.

replace this line sum += num with sum = sum + num .. this is more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM