计算字符串中辅音的数量

counting the number of consonants in a string

我的objective是统计一个String中辅音ONLY的个数,这是我的代码:

import java.io.*;
/**
 * Write a description of class Program46 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Program46
{
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter phrase: ");
        String phrase=br.readLine();
        int lth=phrase.length();
        int ctr=0;
        for(int i=0;i<=lth-1;i++)
        {
            char a=phrase.charAt(i);
            boolean chk=Character.isDigit(a);
            if(a!='a'&&a!='e'&&a!='i'&&a=='o'&&a!='u'&&a!=' '&& chk==false)
                ctr++;

        }
        System.out.println("No. of consonents: "+ctr);
    }
}

程序编译通过,没有语法错误。 但是,当我在 void main() 中执行此操作时, 无论我输入什么,它计算的辅音数量始终为 0。 我的程序有错误吗?如果是这样,我请求你提出一个更好的方法来做到这一点,或者更正上面代码的方法。

您不小心检查了当前字符 'o' (a=='o'),而不是检查它 不是' t (a != 'o').

解决这个问题,你应该没问题。

顺便说一句,请注意 Java 中 main 方法的正确签名是 public static void main(String[] args).

您的代码有两处错误:

  1. 您在检查元音 'o' 时输入错误。而不是a == 'o',应该是a != 'o'
  2. 即使您修复了此问题,您的检查也只会考虑小写元音、space 字符和数字。如果被检查的字符不是这些中的任何一个,那么它将被视为辅音。这包括大写元音、特殊字符(!@#$ 等...)、其他 space 字符('\t')和标点符号。

更正可能是这样的:

public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter phrase: ");
    String phrase = br.readLine();
    int lth = phrase.length();
    int ctr = 0;
    for (int i = 0; i <= lth - 1; i++) {
        char ch = phrase.charAt(i);
        // Skip this character if it's not a letter
        if (!Character.isLetter(ch)) {
            continue;
        }

        if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' &&
            ch != 'A' && ch != 'E' && ch != 'I' && ch != 'O' && ch != 'U' ) {
            ctr++;
        }
    }
    System.out.println("No. of consonents: " + ctr);
}

达到这一点后,您可以查看 "improving" 代码的方法。