0

我想将 OBJ 模型加载到 OpenGL 中。但是我在获取有关模型的数据时遇到问题,当我读取文件时,我收到此错误:

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)

这是我的 OBJLoader 类中的代码:

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;
    }
}

有人可以告诉我如何解决这个问题吗?

PS我对正则表达式和那种格式有点陌生。

4

1 回答 1

1

似乎您的模型顶点定义行在“v”指令之后包含多个空格。你期望这个:

"v -1.0 1.0 1.0"

但模型包含这个:

"v    -1.0 1.0 1.0"

所以你的代码不能处理这种情况。

尝试像这样解析:

    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));
于 2013-07-15T13:54:56.523 回答