【问题标题】:2d Arrays Integer Sequence二维数组整数序列
【发布时间】:2017-07-22 23:40:40
【问题描述】:

我正在尝试计算整数出现在二维数组中的次数并打印计数。我是 Java 新手,还在学习。

这是我正在使用的二维数组:

System.out.println("Array\t Nummbers");
    int Array[][] = { { 39, 16, 13, 1, 35, 31, 47 }, { 39, 2, 45, 44, 38, 19, 40 }, { 39, 43, 33, 16, 20, 9, 30 },
            { 42, 23, 26, 27, 1, 48, 47 }, { 18, 25, 47, 31, 46, 36, 20 }, { 21, 34, 19, 6, 4, 25, 29 },
            { 30, 5, 22, 23, 11, 47, 19 }, { 34, 30, 7, 31, 16, 45, 41 }, { 37, 9, 7, 42, 45, 24, 5 },
            { 39, 34, 28, 5, 37, 17, 22 }, { 42, 47, 34, 15, 35, 41, 28 }, { 22, 8, 46, 30, 36, 28, 11 };

我正在使用我在这里找到的以下代码,我做了一些更改,但我仍然无法修复它。

System.out.println("\t" + countCharInRow(Array));
public static Map<Character, Integer> countCharInRow(char[][] myArray) {
 Map<Character, Integer> charOccurences = new HashMap<>();
 Set<Character> rowCharacters = new HashSet<>();
 for(char[] row : myArray) {
    for(char charInArray = row) { // put all the chars on the line in the set
        rowCharacters.add(row);
    }
    for(char charInSet : rowCharacters) {
        Integer occurences = charOccurences.get(charInSet);
        if(occurences == null) { // first occurence
            charOccurences.put(charInSet, 1);
        } else {  // increment
            charOccurences.put(charInSet, occurences.intValue() + 1);
        }
    }
 }
 return charOccurences;
}

有什么建议吗?

【问题讨论】:

  • 问题不是用英文写的。请更好地解释自己。您的意思是您希望该函数生成二维数组中所有整数频率的映射?
  • 谢谢...试图找出并打印每个数字在那个大数组中出现的次数......希望你能理解,对不起我的英语不好!跨度>
  • 那么如果'a'在第一行出现3次,在第二行出现2次,您希望'a': 5被添加到地图中吗?
  • 是的,先生,正是这个..
  • 因此无需先将字符放入集合中。事实上,这将使您最多计算一行中的每个字符一次,因为一个集合没有重复项。本着这种精神添加了答案。

标签: java arrays arraylist 2d


【解决方案1】:
public static Map<Character, Integer> countCharInMatrix(char[][] mat) {
    Map<Character, Integer> charOccurences = new HashMap<>();
    for(char[] row : mat) {
        for(char charInRow : row) {
            Integer occurences = charOccurences.get(charInRow);
            if(occurences == null) { // first occurence
                charOccurences.put(charInRow, 1);
            } else {  // increment
                charOccurences.put(charInRow, occurences.intValue() + 1);
            }
        }
    }
    return charOccurences;
}

【讨论】:

  • 感谢您的回答...与 system.out.print 中的最后一个错误相同的类型 methodFinal 中的方法 countCharInMatrix(char[][]) 不适用于参数(int[ ][]) 当更改为 Int 时,更大的问题就开始了....
  • 如果你发送一个整数矩阵,那么你需要在局部变量和返回类型中将矩阵参数的类型更改为int[] [] CharacterInteger,@987654325 @ 到 int 在两个 for 循环中
  • 感谢您修复了我的 Matrix m8.... 我真的很感激!!!如果我​​的想法可行,我也会将它发送给您以获得更多现金;)玩得开心
  • 你应该知道我的矩阵是由 {1=7, 2=4, 3=3, 4=4, 5=5, 6=4, 7=4, 8=6 创建的, 9=4, 10=1, 11=3, 12=5, 13=4, 15=2, 16=8, 17=8, 18=4, 19=4, 20=3, 21=7, 22 =7, 23=7, 24=2, 25=3, 26=2, 27=4, 28=6, 29=4, 30=6, 31=4, 32=3, 33=4, 34=6 , 35=2, 36=4, 37=4, 38=5, 39=5, 40=3, 41=5, 42=6, 43=3, 44=3, 45=5, 46=4, 47 =8, 48=2, 49=3}
猜你喜欢
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
相关资源
最近更新 更多