0

I am getting Java Exception in thread "main" java.lang.NullPointerException at test.main(test.java:) in the printf line below.

I am entering values on stdin, for example 1 2 Bus then carriage return then another line and I am ending using Ctrl-Z on Windows.

I have put print statements in and the reading in of data appears to work ok. Why am I getting null exception here?

Here is the code:

import java.util.Scanner;

public class test {
    public static class Data
    {
        public Data() {}
        public Data(int v1, int v2, String s1) { n1 = v1; n2 = v2; s = s1; } 
        public int n1; 
        public int n2;
        public String s; 
    };

    public static void main(String[] args) {
        int i = 0;
        int v1, v2;
        v1 = v2 = 0;
        String s;

        Data items[] = new Data[100];

        Scanner input = new Scanner(System.in);

        while(input.hasNext()) {
            switch(i % 3) {
                case 0: v1 = input.nextInt(); break;
            case 1: v2 = input.nextInt(); break;
                case 2: 
                    s = input.next();
                    items[i] = new Data(v1, v2, s);
                    break;
            }
            ++i;
        }
        input.close();

        for(int j = 0; j < i; ++j) {
            //on next line get Exception in thread "main" java.lang.NullPointerException at test.main(test.java:)
            System.out.printf(  "%s\t%d\t%d\n", items[j].s, items[j].n1, items[j].n2);
        }         
    }
}
1
  • Create a control point at the line in question, fire up the debugger and then look at the content of your variables, one of them is most likely null. Commented Jan 11, 2014 at 16:31

1 Answer 1

1

Look at your code, once properly indented:

switch(i % 3) {
    case 0: 
        v1 = input.nextInt(); 
        break;
    case 1: 
        v2 = input.nextInt();
        break;
    case 2: 
        s = input.next();
        items[i] = new Data(v1, v2, s);
        break;
 }
 ++i;

This means that you only initialize items[i] if i % 3 == 2. So 2 out of three elements of the array are null.

But in the last loop, you're trying to print every element, without ever testing for null.

Side note: naming fields s, n1 and n2 is the best way to have unreadable, unmaintainable code. Give meaninful names to your classes and variables.

Sign up to request clarification or add additional context in comments.

2 Comments

I would also like to add that you should probably use a List rather than pre-allocating an array with 100 elements. What if you have more than 100 lines of data, you will end up with an ArrayIndexOutOfBounds exception.
Ah, how dumb, I thought it might be some esoteric Java thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.