用两个参数创建并填充对象数组

时间:2019-06-25 10:12:36

标签: java

我正在努力研究对象和对象数组,遇到以下问题,但我不知道是什么原因造成的。在某些情况下,我正在制作的应用程序有点像计算器。

总结起来,我有两个已经填充的数组。第一个数组包含数字元素开始的索引。第二个数组包含元素本身。我想创建一个对象数组(具有两个属性,这些属性是:索引和元素。

int numericElementCounter; //此时,变量numericElementCounter的值是已知的,并且用于确定数组的长度。 int[] IndexBeginning = new int[numericElementCounter]; //包含每个数值元素的起始索引。 double[] NumericElementsDouble = new double[numericElementCounter]; //包含元素本身。

//这里有一个'for'循环,它填充了上面初始化的数组,但是我怀疑这是问题的一部分,是否会应要求添加它。

NumericElements[] NumericElementsObjects = new NumericElements[numericElementCounter]; //这是初始化对象数组的尝试。

public class NumericElements {

    int IndexStart;
    double NumericElement;

    public NumericElements(int x, double y) {
    int IndexStart = x;
    double NumericElement = y;
    }

}

//This is the 'for' loop that attempts to fill the array of objects.
for(int n=0;n<numericElementCounter;n++){
            System.out.println("The element starts at: " + IndexBeginning[n]);
            System.out.println("The element itself is: " + NumericElementsDouble[n]);
            NumericElementsObjects[n] = new NumericElements(IndexBeginning[n], NumericElementsDouble[n]);
            System.out.println("The object's IndexStart attribute: " + NumericElementsObjects[n].IndexStart + " The object's numericElement attribute: " + NumericElementsObjects[n].NumericElement);
        }

例如输入是: String UserInput = " 234 + 256 + 278 ";

实际输出:

The element starts at 2
The element itself is: 234.0
The object's IndexStart attribute: 0 The object's numericElement attribute: 0.0
The element starts at 8
The element itself is: 256.0
The object's IndexStart attribute: 0 The object's numericElement attribute: 0.0
The element starts at 14
The element itself is: 278.0
The object's IndexStart attribute: 0 The object's numericElement attribute: 0.0

我已尝试以最小化代码的方式,仅在大家觉得缺少某些东西时才提供所需的信息,我将发布整个代码。 期望是针对对象的属性,即要填充的对象数组的一部分。但是它们仍然保持价值0/0.0

3 个答案:

答案 0 :(得分:0)

您做得不错。您的构造函数中只有一个小问题。

//here you shouldn't create a new variable, instead you should assign them to the variable inside your classs
public NumericElements(int x, double y) {
   this.IndexStart = x;
   this.NumericElement = y;
}

答案 1 :(得分:0)

构造函数不正确,您必须使用this

设置属性的值

这是正确的构造函数:

public NumericElements(int x, double y) {
    this.IndexStart = x;
    this.NumericElement = y;
    }

答案 2 :(得分:0)

在您的NumericElements构造器中,您没有将值分配给IndexStart和NumericElement字段。您正在创建新的局部变量,其范围仅限于构造函数。您可以像下面那样修改构造函数,您应该拥有所需的内容:

public NumericElements(int x, double y) {
    this.IndexStart = x;
    this.NumericElement = y;
}

或者您也可以这样做:

public NumericElements(int x, double y) {
    IndexStart = x;
    NumericElement = y;
}

在两种情况下,您将获得相同的结果。通常用于指代同一类的对象的字段和方法。它是对您尝试访问其字段或方法的同一对象的引用。即使没有此代码,代码也可以正常运行,因为Java会为您完成。