有 Java 编程相关的问题?

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

Java方法错误|包含答案

请帮我恢复理智!请看下面的节目。当我调用它时,这个程序运行正常。我想要的结果是:

triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = 28.0

现在我陷入的部分是在while循环中,当t[x].setArea()得到调用时。我无法理解这个方法目前的编写方式出于某种原因,我认为应该这样写:

void setArea() {      
    t[x].area = (t[x].height * t[x].length)/2;
  }

而不是当前的书写方式:

 void setArea() {
    area = (height * length)/2;

因为它怎么知道你指的是特定的t[x],而不是像这样直接调用它

t[x].area  t[x].height  t[x].length

请告诉我你的想法。这很令人困惑

  class Triangle {
  double area;
  int height;
  int length;

  public static void main(String[] args) {
    int x = 0;
    Triangle [] ta = new Triangle[4];

    while (x < 4) {
      ta[x] = new Triangle();
      ta[x].height = (x + 1) *2;
      ta[x].length = x + 4;
      ta[x].setArea();

      System.out.print("triangle "+x+", area");
      System.out.println(" = "+ta[x].area);
      x = x + 1;
    }
    int y = x;
    x = 27;
    Triangle t5 = ta[2];
    ta[2].area = 343;
    System.out.print("y = " + y);
    System.out.println(", t5 area = "+ t5.area);
  }

  void setArea() {
    area = (height * length)/2;
  }
}

共 (1) 个答案

  1. # 1 楼答案

    如果你使用两个类,你需要做的事情会更加清楚:

    三角形对象:

    public class Triangle {
        int height;
        int length;
        double area;
    
        public int getHeight() {
            return height;
        }
    
        public void setHeight(int height) {
            this.height = height;
        }
    
        public int getLength() {
            return length;
        }
    
        public void setLength(int length) {
            this.length = length;
        }
    
    
    
    
        void setArea() {
            area = (height * length) / 2;
        }
    }
    

    主要课程是:

    public class X {
    
        public static void main(String[] args) {
            int x = 0;
            Triangle[] ta = new Triangle[4];
    
            while (x < 4) {
                ta[x] = new Triangle();
                ta[x].height = (x + 1) * 2;
                ta[x].length = x + 4;
                ta[x].setArea();
    
                System.out.print("triangle " + x + ", area");
                System.out.println(" = " + ta[x].area);
                x = x + 1;
            }
            int y = x;
            x = 27;
            Triangle t5 = ta[2];
            ta[2].area = 343;
            System.out.print("y = " + y);
            System.out.println(", t5 area = " + t5.area);
        }
    }
    

    现在你看到你再也无法访问阵列了

    但我建议不要在该区域储存