简体   繁体   English

Java中的简单数字计数器方法

[英]Simple digit counter method in Java

I am trying to create a method that will count the number of occurrences of digits in a string and record them into an array. 我正在尝试创建一种方法,该方法将计算字符串中数字出现的次数并将其记录到数组中。

For example if the string entered into the method is "1223000", then counter[1] =1, counter[2] =2, counter[3] = 1, counter[0] = 3. 例如,如果输入该方法的字符串为“ 1223000”,则counter [1] = 1,counter [2] = 2,counter [3] = 1,counter [0] = 3。

I keep getting a arrayindexoutofbounds error, here is the code I have soo far: 我不断收到arrayindexoutofbounds错误,这是我到目前为止的代码:

//method: count number of occurences for digits
    public static int[] count(String s){

        int[] counter = new int[10];

        for(int j= 0; j < s.length(); j++){
            if (Character.isDigit(s.charAt(j)))
                counter[s.charAt(j)] += 1;
        }

        return counter;
    }

See my comment for how to correct the issue. 请参阅我的评论以了解如何解决此问题。

You should also consider looping the characters of the string directly, rather than tracking the position in the string and using charAt . 您还应该考虑直接循环字符串的字符,而不是跟踪字符串中的位置并使用charAt

For example, 例如,

public static int[] countDigits(final String str) {
  final int[] freq = new int[10];
  for (final char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
      ++freq[c - '0'];
    }
  }
  return freq;
}

Testing the above using the below code results in no error ( java -ea DigitFreqTest ). 使用下面的代码测试以上内容不会导致错误( java -ea DigitFreqTest )。

final String input = "1223000";
final int[] freq = countDigits(input);
assert freq[0] == 3 && freq[1] == 1 && freq[2] == 2 && freq[3] == 1;

Note the above does not support Unicode... in that case, you may wish to instead use Character.getNumericValue . 请注意,以上内容不支持Unicode ...在这种情况下,您不妨使用Character.getNumericValue

public static Map<Integer, Integer> countNumerals(final String str) {
  final Map<Integer, Integer> freq = new HashMap<Integer, Integer>(10);
  for (final char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
      final int num = Character.getNumericValue(c);
      Integer occ = freq.get(num);
      if (occ == null) {
        occ = 0;
      }
      freq.put(num, occ + 1);
    }
  }
  return freq;      
}

Note I had to improvise using a Map<Integer, Integer> because Java does not inherently provide a multiset collection :-( 注意,我不得不使用Map<Integer, Integer>进行即兴创作Map<Integer, Integer>因为Java本身并不提供多集集合:-(

s.charAt(j) will give you the character number for that number, not it's integer value. s.charAt(j)将为您提供该数字的字符编号,而不是整数值。

It's terribly corrected code, but you'll get the right idea: String s = "1223000"; int[] counter = new int[10]; 这是经过严格纠正的代码,但是您将获得正确的主意: String s = "1223000"; int[] counter = new int[10]; String s = "1223000"; int[] counter = new int[10];

    for(int j= 0; j < s.length(); j++){

        if (Character.isDigit(s.charAt(j))) {
            int i = Integer.parseInt(s.substring(j, j+1));
            counter[i] += 1;
        }
            //unter[s.charAt(j)] += 1;
    }</code>

你得到ArrayIndexOutOfBoundsException ,因为s.charAt(j)counter[s.charAt(j)]会返回数量char例如'1' ,然后转换字符使用ASCII所以为int char '1'int 49等出数组索引。

计数器数组(int []计数器)的大小应为s的长度:int [] counter = new int [s.length()];

If you guys want a counter for anything, just turn it into a string, then use the string method .length() to figure out the length, if that's what you're looking for. 如果您想要一个计数器来存放任何内容,只需将其转换为字符串,然后使用字符串方法.length()即可计算出长度(如果您要查找的是该长度)。 And if I'm not mistaken, the length() method returns an integer, so there you go. 如果我没记错的话,length()方法将返回一个整数,然后就可以开始了。 And as shown somewhere on this page, arrays have the same attribute, but that's for how many spaces there are that have things stored in them. 就像此页上的某处所示,数组具有相同的属性,但这是关于存储有多少东西的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM