代码之家  ›  专栏  ›  技术社区  ›  user9181771

计算字符串中的数字-输出未正确打印

  •  -1
  • user9181771  · 技术社区  · 7 年前

    我的问题是计算给定字符串中的数字, 代码如下:

    public static void main(String[] args) {
        String s=" 1 3 4 5 22 3 2";
        int[] counts=count(s);
        for(int i=0;i<s.length();i++) {
            if(counts[i]==1) {
                System.out.println(s.charAt(i) + " appears " + counts[i] +" time");
            }
            else if(counts[i]!=1 && counts[i]!=0) {
                System.out.println(s.charAt(i) + " appears " + counts[i] +" times");
            }
        }
        }
    
    public static int[] count(String s) {
    int count[] =  new int[99];
    
    for(int i=0;i<s.length();i++) {
    if(Character.isDigit(s.charAt(i))){
        ***count[i]++;***
    }
    }
        return count;
    }
    

    所需的输出是,如果x出现多次,则应表示 x出现n次 ,但我的输出是这样的 Undesired Output

    我用粗体标出的部分是我定位问题的地方,我找不到一种方法来访问,如果2多次出现,那么count[2]也必须获得+1的值,我尝试使用从String到Int的转换,但似乎没有任何效果。提前感谢!

    2 回复  |  直到 7 年前
        1
  •  1
  •   bebidek    7 年前

    那么,为什么不把数组的大小设为10并将数据保存在其中呢。诸如此类:

    public static void main(String[] args) {
        String s=" 1 3 4 5 22 3 2";
        int[] counts=count(s);
        for(int i=0;i<10;i++) 
            if(counts[i]==1) {
                System.out.println(i + " appears " + counts[i] +" time");
            }
            else if(counts[i]!=1 && counts[i]!=0) {
                System.out.println(i + " appears " + counts[i] +" times");
            }
    }
    
    public static int[] count(String s) {
        int count[] =  new int[10];
    
        for(int i=0;i<s.length();i++) 
            if(Character.isDigit(s.charAt(i)))
                count[(int)s.charAt(i) - (int)'0']++;
    
        return count;
    }
    
        2
  •  1
  •   RAZ_Muh_Taz    7 年前

    您有正确的检查来查看字符是否为数字,但您没有正确执行的操作是增加正确的索引。您希望将字符转换为数字,并将该数字用作索引。试试这个

    public static int[] count(String s) {
        int count[] =  new int[10];
    
        for(int i=0;i<s.length();i++) {
            if(Character.isDigit(s.charAt(i)))
            {
                count[Character.getNumericValue(i)]++;
            }
        }
        return count;
    }