字符串中的Java缺点数不起作用

时间:2019-03-14 20:38:32

标签: java string character

我正在尝试查找字符串中辅音的数量。以下是该方法的代码,但是在运行该方法时,它始终返回0。我在用!错误?我是否需要针对每个案例进行处理?即:!(ch ==('a'))|| !(ch ==('o'))

public int numCons() {
    int i = 0;
    int length = quote.length();
    int con = 0;
    String string;

    for (i = 0; i < length; i++) {
        //string = quote.substring(i);
        char ch = quote.charAt(i);

        if (!(ch == ('a') || ch == ('e') || ch == ('i') 
                || ch == ('o') || ch == ('u') || ch == ('y') || ch == ('A') 
                || ch == ('E') || ch == ('I') || ch == ('O') || ch == ('U') || ch == ('Y'))) 
            if (Character.isLetter(i)) 
                con++;
        }
    return con;
}

2 个答案:

答案 0 :(得分:5)

i是您要遍历的索引,而不是字符。你可能是说要检查

if (Character.isLetter(ch)) 

答案 1 :(得分:1)

顺便说一句,如果您使用的是Java 8+,则可以使用Stream API在一行中完成此操作:

    private void writeToFile(String data,Context context) {
try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("time.txt", Context.MODE_PRIVATE));
    outputStreamWriter.write(data);
    outputStreamWriter.close();
}
catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
} 

(可能还有一种更优雅的方式,这只是我写的第一件事)