查找字符串中每个数字的出现次数

时间:2010-02-09 02:21:54

标签: java

FYI。我坚持的另一种练习练习。问题是找到字符串中每个数字的出现次数。我觉得我很亲密,但是我得到了一些糟糕的结果。我是初学者,所以如果可能的话,请在我的关卡中保持提示/帮助。谢谢!

这是我到目前为止所做的:

import java.util.Scanner;

    public class Practice5 {
 public static void main(String[] args) {
  Scanner input= new Scanner(System.in);
  System.out.println("Enter a string");
  String s = input.next();

  int[] counts = countNumbers(s);

  String output = "";

  for (int i = 0; i < counts.length; i++) {
   if (counts[i] != 0)
                        {
           output += "Digit" + (char)('0' + i) + " appears " +
           counts[i] + ((counts[i] == 1) + " times\n");
                        }

           }

                System.out.print(output);
           }


 private static int[] countNumbers(String s) {
  int[] counts = new int[10];

  for(int i = 0; i < s.length(); i++) {
   if (Character.isDigit(s.charAt(i)));
   counts[s.charAt(i) - '0']++;
  }
  return counts;
 }
}

确定。现在,如果我输入一个字符串,如“23 t5t6 u76u 232 g1”

我明白了:

2 appears 1 time
3 appears 1 time

这显然是不正确的。它应该是2出现3次,3次出现2次,5次出现1次,等等。任何帮助将不胜感激。

6 个答案:

答案 0 :(得分:4)

您的第一个问题是使用Java扫描程序。如果我没有记错的话,你只是读到第一个子空间到第一个空格。您可能想要遍历整个字符串,因此扫描仪不适合使用。

一旦你得到整个字符串,你仍然有问题。 代码中的主要问题是在读取行

if (Character.isDigit(s.charAt(i)));
你最后有一个分号。 因此,始终执行下一行(更新值的位置)。这是一个问题,因为有时你的角色不是数字,所以索引“character-'0'”可能超出你定义的10。这应该由Java捕获以创建异常。您没有看到此异常,因为您的代码只处理第一个“23”

答案 1 :(得分:1)

删除本声明末尾的分号:

if (Character.isDigit(s.charAt(i)));

您的编码风格会给您带来麻烦。如果你采用一些合理的约定(例如,一致的意图,围绕所有块的大括号,如if / else和for),你就没有问题发现这个错误。

答案 2 :(得分:1)

除了其他人提到的额外分号外,您的输入还包含空格(“”)字符,但您只能读取空格中的第一组字符。您可以使用这样的一行来读取整行输入:

String s = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)).readLine();

您需要使用try / catch块或将“throws java.io.IOException”添加到您的方法中。

答案 3 :(得分:1)

这对于评论来说太长了,所以我把它放在一个答案中,我觉得它很有趣,而且不一定众所周知。

为了完整起见,应该注意我可以输入一个会导致程序崩溃的字符串。你指定一个int []能够容纳10个整数,但你必须知道Unicode字符中有超过10个数字。

所以你的程序应该为ArrayIndexOutOfBoundsException抛出许多数字。

您可以使用以下程序根据Character.isDigit(...)打印所有数字字符(Character.isDigit(...)接受一个int,所以我们循环所有正整数):< / p>

  for (int i = 0; i < Integer.MAX_VALUE; i++) {
    if (Character.isDigit(i)) System.out.println(i + ": " + (char) i);
  }

在我的Java版本上,它返回268这样的数字(实际的位数可以从一个Java版本变化到另一个,具体取决于支持的Unicode的实际版本。)

请注意,isDigit(...)不接受char,而是接受表示Unicode代码点的int。

48 is a digit: 0
49 is a digit: 1
50 is a digit: 2
51 is a digit: 3
52 is a digit: 4
53 is a digit: 5
54 is a digit: 6
55 is a digit: 7
56 is a digit: 8
57 is a digit: 9
1632 is a digit: ٠
1633 is a digit: ١
1634 is a digit: ٢
1635 is a digit: ٣
1636 is a digit: ٤
1637 is a digit: ٥
1638 is a digit: ٦
1639 is a digit: ٧
1640 is a digit: ٨
1641 is a digit: ٩
1776 is a digit: ۰
1777 is a digit: ۱
1778 is a digit: ۲
1779 is a digit: ۳
1780 is a digit: ۴
1781 is a digit: ۵
1782 is a digit: ۶
1783 is a digit: ۷
1784 is a digit: ۸
1785 is a digit: ۹
etc.

答案 4 :(得分:1)

我会给你另一个我创建的简单算法:

public class Ex95 {

    public static void main(String[] args) {
        int [] counts = count("1B2A2137455");
        for (int i = 0; i < counts.length; i++) {
            System.out.println("counts of [" + i + "] is: " + counts[i]);

        }

    }
    public static int[] count(String s){
        int [] counts = new int[10];
        char [] c = s.toCharArray();
        int counter = 0;
        for(int i=0;i<counts.length;i++){
            for(int j=0;j<c.length;j++){

                    if(Character.isDigit(c[j]) && i == Character.getNumericValue(c[j])){
                        counter++;

                }
            }
            counts[i] = counter;
            counter = 0;
        }
        return counts;
    }
}

答案 5 :(得分:0)

您可以使用以下代码获取结果,而不是检查Character.isDigit函数: -

public static void main(String[] args){
    int[] arr = {0,1,2,3,4,5,6,7,8,9};
    String str = "abc123456";
    HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
    for (int i=0;i<10;i++){
        hm.put(arr[i], 0);
    }
    for (int i=0;i<str.length();i++){
        if(hm.containsKey(str.charAt(i) - '0')){
            hm.put(str.charAt(i) - '0', hm.get(str.charAt(i) - '0')+1);
        }
    }
    System.out.println(hm);
}