在一个数组中计算出现次数(Java)

10

我完全被卡住了。我休息了几个小时,似乎无法解决这个问题。这真的很让人沮丧!

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

用户被要求输入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出现了10次”。

我该如何跟踪每个元素在数组中出现的次数?


3
你正在将numbers[i]与numbers[i]进行比较;这总是为真并增加计数... - Constant
还有一个多余的分号。 - The name's Bob. MS Bob.
3
你的意思是“计算重复项”而不是“计算出现次数”吗?在getOccurrences()方法中,你想返回什么类型的整数?请给出一个小数组示例,并展示当传递到你的方法时你期望返回什么。 - Bohemian
2
@Z̷͙̗̻͖̣̹͉̫̬̪̖̤͆ͤ̓ͫͭ̀̐͜͞ͅͅαлγo,你的名字很让人烦恼 :) - Jean-François Savard
@Bohemian 用户被要求输入10个整数,并将这些整数分配给一个数组(因此方法的参数为“numbers”)。假设我输入“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次。 - FrakkinShip
@FrakkinShip 请将此内容添加到您的问题中(单击 edit 链接) - Bohemian
16个回答

0

请尝试以下三种方法,可能会对您有所帮助

方法1:使用2个循环

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0;       
        for(int i=0;i<arr.length;i++){
            for(int j=0;j<arr.length;j++){
                if(arr[i] == arr[j]){  
                    if(j<i){
                        break;
                    }                   
                    count++;
                }               
            } 
            if(count > 0){  
                System.out.println("occurence of "+arr[i]+"  "+(count));                 
                count = 0;
            }
         }         
    }
}

方法二:使用1个循环

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0;  
        int temp = 0;
        for(int i=0;i<arr.length;i++){              
            if(arr[count] == arr[i]){  
                 if(i<count){
                    if(count<arr.length-1)
                       count++;
                     i=0;
                        //  break;
                  }else{
                    temp++;  
                  }
            } 
                               
           if(i == arr.length-1 && temp > 0){
                System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                temp = 0;   
            }
                  
           if(i == arr.length-1 && count<i){
               if(count<arr.length-1)
                  count++;
               i=0;                 
            }        
          }   
    }
}

方式3:使用 Switch 语句

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0; 
        int temp = 0;
        for(int i=0;i<arr.length;i++){ 
              switch(0){
                  case -1:
                  default:
                    if(arr[count] == arr[i]){  
                      if(i<count){
                        if(count<arr.length-1)
                          count++;
                         i=0;
                         break;
                    }else{
                        temp++;  
                    }
                  } 
              }                  
           
            if(i == arr.length-1 && temp > 0){
                System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                temp = 0;   
            }
                  
            if(i == arr.length-1 && count<i){
                if(count<arr.length-1)
                  count++;
                i=0;                 
            }        
         }   
    }
}

0
// i use List<Integer> to solve the problem. it's not a concise way

public static List<List<Integer>> occurence(int[] cards) {

  // first, we create a ArrayList to store the distinct number and its corresponding count value
  //it takes time
  List<List<Integer>> element = new ArrayList<>();

  int tmp=cards[0],  count=0;
  int total = cards.length;

  for(int i=0; i < total; i++) {

    if(i == total -1) {
      if( cards[i] == tmp) {

          List<Integer> l = new ArrayList<>();
          l.add(tmp);
          l.add(count+1);
          element.add(l);
          break;
      }else {
        List<Integer> l = new ArrayList<>();
        l.add(tmp);
        l.add(count);
        element.add(l);

        l = new ArrayList<>();
        l.add(cards[i]);
        l.add(1);
        element.add(l);
        break;
      }

    }

    if(cards[i] == tmp) {
      count++;        
    }else { 
      List<Integer> l = new ArrayList<>();
      l.add(tmp);
      l.add(count);
      element.add(l);

      tmp = cards[i];
      count = 1;  //we already have 1 occurence of cards[i]. i.e. tmp       
    }
  }

  return element;
}

0
import java.util.Scanner;

public class array2 {
    public static void main (String[]args) {
        Scanner input = new Scanner (System.in);
        int [] number = new int [101];
        int c;

        do {

            System.out.println("Enter the integers from 1-100");
            c = input.nextInt();
            number[c]++;

        }while (c != 0);
        for(int i = 0; i < number.length ; i++) {
            if (number[i] !=0) {
                if (number[i] == 1)
                    System.out.println(i + " occurs " + number[i] + " time");
                else
                    System.out.println(i + " occurs " + number[i] + " times "); 

            }
        }
    }
}

0
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 // This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
public class fileopen {
    public static void main(String[] args) {

        String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        List<String> list = new ArrayList<String>();

        String[] country = null;
        Map<String, Integer> hm = new HashMap<String, Integer>();
        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                country = line.split(cvsSplitBy);

                list.add(country[2]);

                System.out.println(country[1]);
            }
            for (String i : list) {
                Integer j = hm.get(i);
                hm.put(i, (j == null) ? 1 : j + 1);
            }
            // displaying the occurrence of elements in the arraylist
            for (Map.Entry<String, Integer> val : hm.entrySet()) {
                if(val.getKey().equals("Error Message")){
                    System.out.println(val.getKey());
                    continue;
                }
                System.out.println(val.getKey() + " " + val.getValue());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1
请添加一些描述,以便原帖作者可以从您的答案中学习,并帮助他理解出了什么问题。 - VPK

0
嵌套循环解决方案,上述代码的结果将是一个包含元素作为键和出现次数作为值的映射。存在一个数组,用于存储该索引是否被访问过,以避免进行下一次迭代。
static Map<Integer, Integer> getDuplicatedCount(int[] data) {

    Map<Integer, Integer> result = new HashMap<>();
    int[] visited = new int[data.length];
    for (int i = 0; i < data.length; i++) {
        for (int j = i + 1; j < data.length; j++) {
            if (data[i] == data[j]) {
                visited[j] =-1;
                if (visited[i] !=-1) {
                    if (result.get(data[i]) == null) {
                        result.put(data[i], 2);
                    } else {
                        result.put(data[i], result.get(data[i]) + 1);
                    }
                }

            }
        }
    }
    return result;
}

-2
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};  

//Array fr will store frequencies of element  
int [] fr = new int [arr.length];  
int visited = -1;  
for(int i = 0; i < arr.length; i++){  
    int count = 1;  
    for(int j = i+1; j < arr.length; j++){  
        if(arr[i] == arr[j]){  
            count++;  
            //To avoid counting same element again  
            fr[j] = visited;  
        }  
    }  
    if(fr[i] != visited)  
        fr[i] = count;  
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接