计算数组中的出现次数 (Java)

新手上路,请多包涵

我完全被难住了。我休息了几个小时,但我似乎无法弄清楚这一点。令人心烦意乱!

我知道我需要检查数组中的当前元素,看看它是否出现在数组的其他地方。这个想法是输出以下内容:

用户被要求输入 10 个整数,这些整数被分配给一个数组(因此“数字”作为该方法的参数)。假设我输入“1、1、2、3、3、4、5、6、7、8”。打印结果应该是“1出现2次。2出现1次。3出现2次。4出现1次。5出现1次。6出现1次。7出现1次。8出现1次。”此打印将以单独的方法完成。

除了我创建的用于计算出现次数的方法外,我的代码中的所有内容都有效。

 public static int getOccurrences(int[] numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
    {
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])
        {
            count++;
        }
    }

    return count;
}

我知道这里有什么问题。我将数组中的当前整数元素设置为变量 currentInt。 if 语句计算数组中的每个整数元素,因此输出为“[I@2503dbd3 occurs 10 times”。

如何跟踪数组中每个元素的出现?

原文由 FrakkinShip 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
1 个回答
package countoccurenceofnumbers;

import java.util.Scanner;
public class CountOccurenceOfNumbers {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int [] num = new int[100];
        int [] count = new int[100];
        //Declare counter variable i
        //and temp variable that will
        //temporarily hold the value
        //at a certain index of num[] array
        int i,temp = 0;
        System.out.println("Enter the integers between 1 and 100: ");

        //Initialize num[] array with user input
        for(i=0; i < num.length; i++){
            num[i] = input.nextInt();
            //expected input will end when user enters zero
            if(num[i] == 0){
                break;
            }
        }//end of for loop

        //value at a given index of num array
        //will be stored in temp variable
        //temp variable will act as an index value
        //for count array and keep track of number
        //of occurences of each number
        for(i = 0; i < num.length; i++){
                temp = num[i];
                count[temp]++;
            }//end of for looop

        for(i=1; i < count.length; i++){

            if(count[i] > 0 && count[i] == 1){
             System.out.printf("%d occurs %d time\n",i, count[i]);
             }
            else if(count[i] >=2){
                System.out.printf("%d occurs %d times\n",i, count[i]);
            }

         }//end of for loop

    }//end of main
    }//end of CountOccurrenceOfNumbers

///////////输出//////////////////////

输入 1 到 100 之间的整数:

2 5 6 5 4 3 23 43 2 0

2 出现 2 次

3 出现 1 次

4 出现 1 次

5 出现 2 次

6 出现 1 次

23 出现 1 次

43 出现 1 次

构建成功(总时间:3 分 23 秒)

原文由 Brenda Mejia 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题