在Java中用构造函数调用数组

时间:2014-07-08 19:08:44

标签: java

我试图在构造函数中调用一个数组并将其分配给变量,如:

private int x1;
private int y1; 
private int x2;
private int y2; 
private int x3;
private int y3;
private int x4;
private int y4; 

int[] array1 = new int[7];

public ChangePlane(String name, int[] array1){ 
this.name = name; 
this.array1 = array1;
array1[0]=x1;
array1[1]=y1;
array1[2]=x2;
array1[3]=y2;
array1[4]=x3;
array1[5]=y3;
array1[6]=x4;
array1[7]=y4;
}

我正在使用这个构造函数来调用一组四个坐标来围绕图像绘制一个正方形。但是代码不起作用。任何帮助,将不胜感激。提前谢谢。

6 个答案:

答案 0 :(得分:1)

考虑传递一个对象而不是数组。该对象可以包含属性。

答案 1 :(得分:0)

当你这样做时:

array1[0]=x1;
array1[1]=y1;
array1[2]=x2;
array1[3]=y2;
array1[4]=x3;
array1[5]=y3;
array1[6]=x4;
array1[7]=y4;

您正在用零填充数组,因为x1,y1等未初始化。

此代码:

int[] array1 = new int[7];

是没用的,因为你将array1作为参数传递给构造函数的数组分配给array1。顺便说一下,当你将x1,y1等分配给数组[0],数组[1]等时......你还要改变作为参数传递的数组。 / p>

答案 2 :(得分:0)

你好像已经改变了作业,

public ChangePlane(String name, int[] array1){ 
  this.name = name; 
  this.array1 = array1;
  x1 = array1[0];
  y1 = array1[1];
  x2 = array1[2];
  y2 = array1[3];
  x3 = array1[4];
  y3 = array1[5];
  x4 = array1[6];
  y4 = array1[7];
}

假设您正在将int[] array1 = new int[8];(因为array1 [7]将失败)传递给您的构造函数。

答案 3 :(得分:0)

您应该定义名为 name 的类变量。你在哪里分配了这个名字?

答案 4 :(得分:0)

public class Square {
  private String name;
  private int[] points;

  public Square(String name, int[] points){ 
    this.name = name; 
    this.points= points;
  }

  public String getName() {
    return name;
  }

  public int[] getPoints() {
    return points;
  }
}

使用名称和点

创建一个Square对象
Square square = new Square("first", new int[]{1, 2, 3, 4, 5, 1, 2, 3, 4})

只要您想访问这些点,就可以使用该对象

square.getPoints()

答案 5 :(得分:0)

那么你需要考虑很多事情:

private int x1; // Why would you set those integers as private 
private int y1; // if they are just used to initiate your array's values 
private int x2;
private int y2; 
private int x3;
private int y3;
private int x4;
private int y4; 

int[] array1 = new int[7]; // your array might as well be private if you intent
// to use it through the whole class

public ChangePlane(String name, int[] array1){ 
this.name = name; // this.name isn't define in the class' private parameters, it doesn't exists
this.array1 = array1; // this array should be private
array1[0]=x1; // how are the x values inputed in your program?
array1[1]=y1;
array1[2]=x2;
array1[3]=y2;
array1[4]=x3;
array1[5]=y3;
array1[6]=x4;
array1[7]=y4;
}