如何将数组对象的值相加?
我有一个创建了 5 个对象的数组。每个对象都有两个字符串和一个 int。我们将 int 称为“数字”。我如何将每个对象的“数字”添加到最终数字中,假设数字发生变化,所以我不能简单地输入 5 + 3 等。例如
Question question[] = new Question[5];
public Constructor()
{
String1 = "null";
Sting2 = "null";
number = 0;
}
,我有五个看起来像这样的对象,它们都有一个不同的价值。数字指的是分数,所以如果用户做对了,数字将被添加到一个变量中,我需要知道当我以类似的方式执行 5 个对象时如何将 5 个变量相加。
for (i=0; i < Question.length; i++)
{
object.dostuff
}
I have an array that created 5 objects. Each object has two strings and a int. Lets call the int "number". How can i add up the "number's" of each object into a final number, assume that the numbers change so i cannot simply just put 5 + 3 etc.. For example
Question question[] = new Question[5];
public Constructor()
{
String1 = "null";
Sting2 = "null";
number = 0;
}
SO i have five objects that look like this, they all have a different value. Number refers to a score, So if the user does something right, the number will be added to a variable, i need to know how to add up the 5 variables when i execute the 5 objects in something like.
for (i=0; i < Question.length; i++)
{
object.dostuff
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
许多事情必须首先发生:
希望这会有所帮助(如果这是一个与作业相关的问题,您应该这样标记它,这将最大化您在这里获得帮助的机会)。
Many things have to happen first:
Hope this helps (if this is a homework related question you should tag it as such, that would maximize your chance to get help here).
不要使用 Question.length,使用 Question.length
添加一个访问器方法和一个增加分数的方法。
Don't use Question.length, use question.length
Add an accessor method and a method to increment the scores.
使用map从元组列表中提取数字,然后使用reduce对数字进行累加求和。
输出:
use map to extract the numbers from the list of tuples then use reduce to accumulatively sum the numbers.
output: