简体   繁体   English

如何计算字符串中的数字

[英]How to count the digits in a String

The code is close to correct, but I cannot see how I can move from System.out.println to a toString() method here, what am I missing? 代码接近正确,但是我看不到如何从System.out.println移到toString()方法,我缺少什么?

import java.util.Scanner;

class Histogram
{
    private int[] numCount;
    int size=0;

    public Histogram(String line)
    { 
        setList(line);
    }

    public void setList(String line)
    {
        numCount = new int[20];

        for(int i=0;i<10;i++)
            numCount[i]=0;

        Scanner chopper = new Scanner (line);
        while (chopper.hasNextInt())
        {
            int num = chopper.nextInt();
            numCount[num]++;
        }

        for(int i=0;i<10;i++)
            System.out.println(i+"::"+numCount[i]);

        System.out.println();
        System.out.println();
    }
}

First, in setList() the default value of the primitive int is 0. And if you're using decimal math you only need 10 digits. 首先,在setList()中,原始int的默认值为0。并且,如果您使用的是十进制数学运算,则只需10位数字。 And remove the println (s); 并删除println

public void setList(String line) {
    numCount = new int[10]; // <-- base 10
    Scanner chopper = new Scanner(line);
    while (chopper.hasNextInt()) {
        int num = chopper.nextInt();
        numCount[num]++;
    }
    // once the loop is done, you can do
    System.out.println(this); // <-- will call toString so
}

Next override toString() . 接下来覆盖toString() You might use Arrays.toString(int[]) which Returns a string representation of the contents of the specified array like 您可以使用Arrays.toString(int[]) ,它返回指定数组内容的字符串表示形式,例如

@Override
public String toString() {
    return Arrays.toString(numCount);
}

Finally, I personally would have preferred an implementation of setList(String) like 最后,我个人更喜欢setList(String)的实现,例如

private int[] numCount = new int[10]; // <-- base 10

public void setList(String line) {
    for (char ch : line.toCharArray()) {
        numCount[Character.digit(ch, 10)]++;
    }
}

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

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