1

I am very new at this so I apologize if this may seem very basic. Anyway I am trying to read input from a file and put that data into an array so that I can graph it later. the problem I am having is putting the labels of the data into an array.

Here is what I have currently:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class P6 {

    static String titlePie = "Pie Chart";
    static int numElements;
    static String[] labels;
    static double[] dataPieElements;

    public static void main(String[] args){

        P6 p6 = new P6();
        p6.readFile(args[0]);
        System.out.println(numElements);
        System.out.println(Arrays.toString(dataPieElements));
        System.out.println(Arrays.toString(labels));
    }

    private void readFile(String inputFile) {
        try {
            Scanner in = new Scanner(new File(inputFile));
            while (in.hasNext()){
                numElements=in.nextInt();
                if (in.hasNextDouble()){
                    for (int i = 0; i<numElements; i++){
                        dataPieElements[i]=in.nextDouble();
                    }
                }
                else if (in.hasNext()){
                    for (int i = 0; i<numElements; i++){
                        labels[i]=in.next();
                    }
                }
            }
            in.close();
        }
        catch (FileNotFoundException e){
            System.out.println("File not found");
        }
    }
}

The input file looks like this:

6
Nokia
Apple
Google
Samsung
Apple
Other
14.2
26.2
13.1
18.9
11.3
16.3

The error I'm getting is: Exception in thread "main" java.lang.NullPointerException

So my thinking is that because the doubles are after the strings the pointer reaches the end of the file and never gets the strings, but if I change the order of the if statements and get the strings before the doubles it turns the doubles into strings. So what is the best way to get each data type into its respective array?

Thank you so much for any suggestions you might have!

1 Answer 1

1

You declared your arrays labels and dataPieElements, but you didn't initialize those arrays, so they're still null.

Initialize them when you know how many are needed. After

numElements=in.nextInt();

then...

labels = new String[numElements];
dataPieElements = new double[numElements];
Sign up to request clarification or add additional context in comments.

Comments

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.