首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java,从文件中读取x,y,z坐标

Java,从文件中读取x,y,z坐标
EN

Stack Overflow用户
提问于 2018-09-21 03:21:09
回答 1查看 498关注 0票数 0

我正在制作由三角形组成的3D对象。这些三角形有3个矢量。现在我有了一个包含许多数字的文件...如果一条线以"v“开头,则这条线具有Vector的x、y和z坐标。如果一行以"f“开头,该行包含我的三角形所需的.txt文件中的向量所在的行。该文件首先以全“v”开头,然后以“f”开头。

示例:(开头的数字就是这行)

21 v 1.2000 0.20000 -1.0000 -> Vector1(1.2,0.2,-1)

22 v 1.2000 0.20000 1.00000 -> Vector2(1.2,0.2,1)

23伏-1.200 -0.2000 1.00000 -> Vector3(-1.2,-0.2,1)

..。

71 f 21 23 22 ->三角形(Vector1、Vector3、Vector2)

这就是我尝试的方法,显然不起作用,因为我是一个Java新手:P

代码语言:javascript
复制
public static ArrayList<Triangle> mesh = new ArrayList<>();

public static void loadObject(String fileName) {
    try {
        Scanner scan = new Scanner(fileName);
        ArrayList<Vector> vectors = new ArrayList<>();

        while (scan.hasNextLine()) {
            if (scan.equals("v")) {
                Vector v = new Vector();
                int i = 0;
                while (scan.hasNextDouble() && i < 3) {
                    if (i == 0) {
                        v.setX(scan.nextDouble());
                    }
                    if (i == 1) {
                        v.setY(scan.nextDouble());
                    }
                    if (i == 2) {
                        v.setZ(scan.nextDouble());
                    }
                    i++;
                }
                vectors.add(v);
            }
            if (scan.equals("f")) {
                Triangle t = new Triangle();
                int j = 0;
                while (scan.hasNextInt() && j < 3) {
                    if (j == 0) {
                        t.setVec1(vectors.get(scan.nextInt() - 1));
                    }
                    if (j == 1) {
                        t.setVec2(vectors.get(scan.nextInt() - 1));
                    }
                    if (j == 2) {
                        t.setVec3(vectors.get(scan.nextInt() - 1));
                    }
                    j++;
                }
                mesh.add(t);
            }
        }
    } catch (Exception e) {

    }
}

谢谢你的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-21 03:53:33

这样如何:

代码语言:javascript
复制
static List<Triangle> parse(String fileName) 
{
  List<Triangle> mesh = new ArrayList<>();  
  Map<String, Vector> vm = new HashMap<>();

  try (Scanner scan = new Scanner(new FileReader(fileName)))
  {
    while(scan.hasNextLine()) 
    {
      String[] p = scan.nextLine().split("\\s");
      if("v".equals(p[1]))
      {
        vm.put(p[0], new Vector(Double.parseDouble(p[2]), Double.parseDouble(p[3]), Double.parseDouble(p[4])));
      }
      else if("f".equals(p[1]))
      {
        mesh.add(new Triangle(vm.get(p[2]), vm.get(p[3]), vm.get(p[4])));
      }
    }
  }
  catch(IOException e)
  {
    e.printStackTrace();
  }
  return mesh;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52431907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档