查找和计算大写字母

Zac*_*ach 0 java string methods replace

我写了一个方法来检查大写字母的字符串,如果它发现一个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;
    }
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 5

你需要一个明确的检查msg.length() > 0.它可以是一个空字符串,这将导致异常.

(您也可以省略该replaceAll(..)部分,它不会帮助您找到大写字母的数量)