【问题标题】:track how many numbers and counter in array跟踪数组中有多少个数字和计数器
【发布时间】:2011-06-03 00:31:52
【问题描述】:

我需要知道每个人有多少票。我有一个计数,计算有多少候选人在比赛中是 5。现在我有一堆来自数组列表的数字,我需要计算每个候选人的快乐投票,候选人的数量根据我使用的数组列表而变化,但是出于测试目的,我使用的是 test5,它有 5 个。

 //Numbers from arraylist:
1
1
2
5
2
5
5
5

这是我的代码

// My code
for (int i=1; i <output.size(); i++){
        char checkBallot = output.get(i).charAt(1); 
        //candidate is array to track how many output as what 
                    // output is array of numbers I want to count. 
        String aString = Character.toString(checkBallot);
        int c = Integer.parseInt(aString);
        int b = c; 
        for (int p= 0; p < count; p++){
            if(c == p+1){
                int oldvalue =0; 
                candidate[c] = c+ oldvalue ;
                oldvalue = c ;
                System.out.println("this is the counter:" +c);
            }

        }

【问题讨论】:

  • 另外,粘贴其余代码...输出是什么?状态?候选人?等
  • 输出是数组列表中的数字,状态是现在状态的顺序是1。候选者是一个数组,用于跟踪输出中有多少 1 2 3 4 5。抱歉,我写我想要达到的目标很糟糕。
  • @oli 我想计算输出数组列表中有多少个 1,2,3,4,5。并将每个的数量存储到候选中。

标签: java arrays counter


【解决方案1】:

我认为您应该摆脱 oldvalue 并使用 ++candidate[c]; 而不是这三行。假设我理解你的代码,而我几乎不理解。

【讨论】:

    【解决方案2】:

    计算输出数组列表中有多少个 1、2、3、4、5:如果你有一个整数数组列表:

    final int[] candidate = new int[count];
    for(int i : output)
        candidate[i]++;
    

    假设“count”是您在 ArrayList 中可能找到的最大值。

    相反,如果你有一个字符串数组列表,那么你写

    final int[] candidate = new int[count];
    for(String i : output)
        candidate[Integer.parseInt(i)]++;
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 2017-05-15
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多