有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中通过point类读取多个点?

public class point3d {
float x;
float y;
float z;  
public point3d(float x, float y, float z){
   this.x = x;
   this.y = y;
   this.z = z;
}
public point3d(){
    x = 0;
    y = 0;
    z = 0;
}
public float getX(){
    return x;
}
void setX(float x) {
    this.x =x;
}
public float getY(){
    return y;
}
void setY(float y) {
    this.y =y;
} 
public float getZ(){
    return z;
}         
void setZ(float z) {
    this.z = z;
}
public String toString()
{
    return "(" + x + ", " + y + "," + z + ")";
}        
}

这是我编写的一个point3d类代码,我想通过这个point3d类读取多个点,这些点在主类中给出,我如何实现这一点。请帮帮我好吗


共 (2) 个答案

  1. # 1 楼答案

    首先,根据Naming Conventions,类应该以大写字母开头

    其次,应该在主类中为Point3d创建一个容器,例如List

    接下来,您可以迭代它并执行您的逻辑

    List<Point3d> points = new ArrayList<>(); // this is JDK7
    List<Point3d> points = new ArrayList<Point3d>(); // this is before JDK7, pick one
    
    points.add(new Point(4F, 3F, 2F)); // let's create some points to iterate over
    points.add(new Point(23F, 7F, 5F));
    
    for(Point3d point : points) {
        // do some logic with point
    }
    

    接下来的问题是,你想用这些points实现什么

  2. # 2 楼答案

    我想我现在明白你的问题了。你想制作一个三维矩形,这意味着你需要4个点(除非你想让它也有深度,在这种情况下你需要8个)

    所以你只需要一个由4个point3d类组成的数组:

    point3d[] rectangle = new point3d[4];
    

    然后你只需要分配给这个数组:

    rectangle[0] = new point3d(x,y,z); //note that the first element is 0, not 1
    rectangle[1] = new point3d(x2,y2,z2);
    ...
    

    当您以后想要访问它们时:

    System.out.println(rectangle[0].getX());
    

    我建议你读一读:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html