I’m new to Java, so the concepts and terminology are fuzzy, but I’m trying! I need to create a class that will take data in a string, parse it and return an object (array) with member attributes that can be accessed from the main class. I’ve read that this is a better solution than having multiple indexed arrays like pointx[], pointy[], pointz[], etc.., especially if you need to perform operations like swapping or sorting.
So, I’d like to access the array object’s members from main with something like test[0].x, test[100].y, etc. however, I’m frustratingly getting an Exception in thread "main" java.lang.NullPointerException and I don’t understand how to proceed.
Here’s how I’m calling parse from main:
parse a = new parse();
parse[] test = a.convert("1 2 3 4 1 2 3 4 1 2 3 4"); // <- ** error here **
System.out.printf("%.2f %.2f %.2f %d\n", test[0].x, test[0].y, test[0].z, test[0].r);
Here’s the parse class:
public class parse {
parse[] point = new parse[1000];
public float x;
public float y;
public float z;
public int r;
parse() {
}
public parse[] convert(String vertices) {
// parse string vertices -> object
point[0].x = 10; // <- ** error here **
point[0].y = 100;
point[0].z = 50;
point[0].r = 5;
return point;
}
}
Thanks in advance for any help specifically with my parse class & any related java pointers to continue my learning java and enjoyment of programming!
When you create an array of
parseobjects the array itself is empty and doesn’t actually contain any objects, only null references. You also need to create the objects themselves and store them in the array.Furthermore, your
pointis a member of yourparseclass when it should be a local variable of yourconvertmethod, which itself should bestatic, since it doesn’t rely on a particular instance.You would then invoke the conversion as follows:
Here’s the parse class: