0

我编写了一种方法来检查字符串中的大写字母,如果发现一个 int 计数增加 1。但是当我测试该方法时,我被告知不允许除以 0。它不应该是 0 .. 任何人都可以阐明这一点吗?

    public final boolean findIfCaps(String msg)
    {
        int count=0;
        msg = msg.replaceAll("\\W","");
        for(int x=0;x<msg.length();x++){
            if(Character.isUpperCase(msg.charAt(x)))
                count++;
        }
        double percent = count/msg.length();
        if(percent>0.5)
           return true;
        return false;
    }
4

1 回答 1

5

You need an explicit check if msg.length() > 0. It can be an empty string, which would lead to the exception.

(You can also omit the replaceAll(..) part, it doesn't help you with finding the number of capital letters)

于 2013-08-14T19:01:26.533 回答