簡體   English   中英

計數 Integer 出現在二維數組中 Java

[英]Counting Integer Occurrence in a 2D Array in Java

給定用戶輸入,我正在嘗試計算 Java 中二維數組中整數出現的次數。我將其與一維數組一起使用,並認為我可以重構代碼以使其與二維數組一起使用. 我的代碼運行了,但我無法讓它工作。 有人可以幫我弄清楚我哪里出錯了嗎?

package test.code;

import java.util.Scanner;

public class TestCode {

    public static void main(String[] args) {
        //Create new scanner object
        Scanner userInput = new Scanner(System.in);
        //Declare two dimentional array
        int[][] num2d = new int[4][3];
        int[][] duplicate = new int[4][3];

        //Declare variables
        int i;
        int j;
        int k;
        int count;
        final int x = -1;
        //Print to screen asking for user input
        System.out.print("Enter seven numbers: ");

        for (i = 0; i < 4; i++) {
            for (j = 0; j < 3; j++) {
                num2d[i][j] = userInput.nextInt();
                duplicate[i][j] = x;
            }
        }
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 3; j++) {
                count = 1;
                for (k = i + 1; k < 10; k++) {
                    if (num2d[i][k] == num2d[j][k]) {
                        count++;
                        duplicate[i][j] = 0;
                    }
                }
                if (duplicate[i][j] != 0) {
                    duplicate[i][j] = count;
                }
            }
        }
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 3; j++) {
                if (duplicate[i][j] != 0) {
                    System.out.println("Number " + num2d[i][j] + " occurs " + duplicate[i][j] + " times.");
                }
            }
        }
    }
}

我假設您只想要 num2d 中每個人num2d的確切出現次數。

為此,我將使用數據結構Map請參閱此處的文檔 現在您可以將二維數組轉換為Map 重復項將存儲在Map中,其中鍵是 integer 值,map 值是該 integer 的實例數。

Map<Integer, Integer> duplicates = new HashMap<Integer, Integer>();
int currentIntValue;
for (i = 0; i < 4; i++) {
   for (j = 0; j < 3; j++) {
      currentIntValue = num2d[i][j]);      
      if(duplicates.KeySet().contains(currentIntValue)) {
         duplicates.put(currentIntValue, duplicates.get(currentIntValue) + 1); //Integer already in map, inc the count value
      } else 
      {
         duplicates.put(currentIntValue, 1); //Integer not in map, add it with count 1
      }
      
   }
}

現在您可以通過以下行輕松獲得 integer 的計數


duplicates.get(1); //Will return the count for integer 1

然而,這使得 2D 冗余,你可以更輕松地循環遍歷userInput的數量而不是首先將它們添加到 2D 數組,我真的不明白num2d的目的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM