java - 使用两个参数创建和填充对象数组
问题描述
我正在逐步使用对象和对象数组,遇到以下问题,我无法弄清楚是什么原因造成的。在某些情况下,我正在制作的应用程序有点像计算器。
总结一下,我有两个已经被填充的数组。第一个数组包含数字元素开始位置的索引。第二个数组包含元素本身。我想创建一个对象数组(具有两个属性,属性是:索引和元素。
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
解决方案
你做得很好。您的构造函数中只有一个小问题。
//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;
}
推荐阅读
- botframework - 收到后立即从“UnmixedMeetingAudio”缓冲区创建转录 - 具有应用程序托管媒体的机器人
- r - 根据具有不同字符串的不同行制作数据框的子集
- javascript - 有没有办法在事件发生后自动重新加载/刷新本地主机上的烧瓶网页?
- ansible - Ansible 替换单引号正则表达式
- image-processing - 如何从目录中绘制图像数据集的混淆矩阵?
- .net-core-3.1 - 无法使用 SSO 登录 - NOSTATE SimpleSaml (ITfoxtec.Identity.Saml2)
- neo4j - 无法使用 Neo4j 连接器在 PowerBI Desktop 中连接 Neo4j Desktop
- python - 获取以符号调用或标有 $ 符号的列表项
- javascript - 如何将参数从 JS 传递到 Power bi Embedded?
- swift - 将 shadowPath 添加到 UITableView 子类