首页 > 解决方案 > 使用两个参数创建和填充对象数组

问题描述

我正在逐步使用对象和对象数组,遇到以下问题,我无法弄清楚是什么原因造成的。在某些情况下,我正在制作的应用程序有点像计算器。

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

int numericElementCounter; // 变量 numericElementCounter 的值此时是已知的,它用于确定数组的长度。 int[] IndexBeginning = new int[numericElementCounter];//包含每个 Numeric 元素的起始索引。 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

标签: java

解决方案


你做得很好。您的构造函数中只有一个小问题。

//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;
}

推荐阅读