I want to load OBJ models into OpenGL. But I am having a problem getting the data about the model, when I read the file, I get this error:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Float.valueOf(Float.java:417)
at game.trippylizard.OBJLoader.loadModel(OBJLoader.java:18)
at game.trippylizard.MainScreen.<init>(MainScreen.java:39)
at game.trippylizard.MainScreen.main(MainScreen.java:71)
This is the code in my OBJLoader class:
public class OBJLoader {
public static Model loadModel(File f) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader(f));
Model m = new Model();
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("v ")) {
float x = Float.valueOf(line.split(" ")[1]); //Error is here
float y = Float.valueOf(line.split(" ")[2]);
float z = Float.valueOf(line.split(" ")[3]);
m.vertices.add(new Vector3f(x,y,z));
} else if (line.startsWith("vn ")) {
float x = Float.valueOf(line.split(" ")[1]);
float y = Float.valueOf(line.split(" ")[2]);
float z = Float.valueOf(line.split(" ")[3]);
m.normals.add(new Vector3f(x,y,z));
} else if (line.startsWith("f ")) {
Vector3f vertexIndices = new Vector3f(
Float.valueOf(line.split(" ")[1].split("/")[0]),
Float.valueOf(line.split(" ")[2].split("/")[0]),
Float.valueOf(line.split(" ")[3].split("/")[0])
);
Vector3f normalIndices = new Vector3f(
Float.valueOf(line.split(" ")[1].split("/")[2]),
Float.valueOf(line.split(" ")[2].split("/")[2]),
Float.valueOf(line.split(" ")[3].split("/")[2])
);
m.faces.add(new Face(vertexIndices, normalIndices));
}
}
reader.close();
return m;
}
}
Could someone tell me how to fix this?
P.S. I'm kinda new to regex and that kind of formatting.
It seems that your model Vertex definition lines contain more that one space after "v" directive. You expect this:
"v -1.0 1.0 1.0"
but model contains this:
"v -1.0 1.0 1.0"
so your code doesn't handle such a situation.
Try to parse like this:
String arr[] = line.substring(2).trim().split(" ");
float x = Float.parseFloat(arr[0]);
float y = Float.parseFloat(arr[1]);
float z = Float.parseFloat(arr[2]);
m.vertices.add(new Vector3f(x,y,z));