【问题标题】:Adding through vectors通过向量添加
【发布时间】:2013-12-13 13:33:08
【问题描述】:
public static void main(String[] args)
    {
        Vector vec = new Vector();

        vec.add(new Team(1, "Manchester City", 38, 64, 89));
        vec.add(new Team(2, "Manchester United", 38, 56, 89));
        vec.add(new Team(3, "Arsenal", 38, 25, 70));
        vec.add(new Team(4, "Tottenham", 38, 25, 69));
        vec.add(new Team(5, "Newcastle", 38, 5, 65));

        int points = 0;
        int total = 0;

        for(int i = 0; i < vec.size(); i++)
        {
            points = ((Team) vec.elementAt(i)).getPoints();
            total += points;
        }
        System.out.println("Total Points: " + points);


    }

谁能帮帮我,我要做的就是将我的对象中最后一个参数的所有值加在一起。

我下面的只是打印出最后一个对象的值(65)。

我会说这是我做错的一些小事,但如果有人可以为我指出,那就太好了。

【问题讨论】:

  • System.out.println("Total Points: " + total);

标签: java object vector addition


【解决方案1】:
 System.out.println("Total Points: " + points);
                                        |
                                        look here it should be total.

像这样改变。

 System.out.println("Total Points: " + total);

改变

points = ((Team) vec.elementAt(i)).getPoints();
total += points;

points += ((Team) vec.elementAt(i)).getPoints();
total = points;

【讨论】:

  • 哈哈,我现在觉得很傻,我猜我今天不在。感谢普拉巴卡兰的帮助
  • @user2757842 如果您觉得有帮助,请将其标记为答案
  • 我刚去那里,需要先等 9 分钟哈
【解决方案2】:

您可以使用 foreach 代替 for:

for(Object t:vec)
{
    total += ((Team)t).getPoints();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2018-09-15
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多