I've created a class with a few objects.
class SalesPerson {
String number;
String name;
double salesAmount;
}
So now I need to copy some data from a text file to an array.
"sales.txt"
S0001
Alice
2000
S0002
Bob
3400
S0003
Cindy
1200
S0004
Dave
2600
Below is the shortened version of my code, assuming that the getName(s), setName(s) and constructors are created and the text file can be successfully read:
class ArrayImport {
public static void main(String args[]) throws FileNotFoundException {
String fileName = "sales.txt";
SalesPerson sp = new SalesPerson[4]; //Manually counted
//Read the file
Scanner sc = new Scanner(new FileReader(fileName));
//Copy data to array
int i = 0;
while (sc.hasNext()) {
sp[i].name = sc.nextLine(); //Error starts here
sp[i].number = sc.nextLine();
sp[i].salesAmount = Double.parseDouble(sc.nextLine());
i++;
}
}
}
I get the error message "Exception in thread "main" java.lang.NullPointerException..." pointing to the line which I commented "Error starts here".
So I am guessing that this is not the way to assign a value to an object array, and if my guess is correct, what are the correct syntax?