I don't know about that invalid cast exception. public double getBlankness(String str) { int falce = 0; for(int i = 0; i < str.length; ++i) { if( !str.substring(i, i).contains(" ") ) falce++; } str += " "; falce += true; return falce/str.length; }