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!