-1

我按照 Dan 的建议更改了我的代码,我现在可以编译该程序,但是,无论输入是什么,结果始终为 2。我将该程序的第二部分放在新代码的下方。请帮忙。

这是新代码。

    public class VowelCons 
        {
    private final String str;
    private final int totalConsonants;
    private final int totalVowels;

        public VowelCons(final String s) 
    {
             this.str = s;
                int totalConsonants = 0;
                int totalVowels = 0;
                if (null != s) 
        {
                    for (final char c : s.toCharArray()) 
            {
                                switch (c) 
                    {
                                        case 'A':
                                        case 'a':
                                        case 'E':
                                        case 'e':
                                        case 'I':
                                        case 'i':
                                        case 'O':
                                        case 'o':
                                        case 'U':
                                        case 'u':

                        totalVowels++;
                                            break;

                        default:

                        if (Character.isLetter(c)) 
                        {
                                                    totalConsonants++;
                                            }
                                            break;
                                    }
                        }
                }
            this.totalConsonants = totalConsonants;
            this.totalVowels = totalVowels;
        }


    public String getString() 
    {
             return str;
    }

    public int getNumConsonants() 
    {
                return this.totalConsonants;
    }

    public int getNumVowels() 
    {
                return this.totalConsonants;
    }
}

该程序的另一部分获取用户的输入并将其传递给此类。这是代码。【此部分不能按规定更改

    import java.util.Scanner;

    public class VowelConsCounter
    {
        public static void main(String[] args)
        {
         String input;        // User input
         char selection;      // Menu selection

         Scanner keyboard = new Scanner(System.in);

         System.out.print("Enter a string: ");
         input = keyboard.nextLine();

         VowelCons vc = new VowelCons(input);

        do
        {
          selection = getMenuSelection();

          switch(Character.toLowerCase(selection))
          {
            case 'a' :  System.out.println("\nNumber of vowels: " +
                        vc.getNumVowels());
                        break;
            case 'b' :  System.out.println("\nNumber of consonants: " +
                        vc.getNumConsonants());
                        break;
            case 'c' :  System.out.println("\nNumber of vowels: " +
                        vc.getNumVowels());
                        System.out.println("Number of consonants: " +
                        vc.getNumConsonants());
                        break;
            case 'd' :  System.out.print("Enter a string: ");
                        input = keyboard.nextLine();
                        vc = new VowelCons(input);
         }

      } while (Character.toLowerCase(selection) != 'e');

   }

   public static char getMenuSelection()
   {
      String input;     
      char selection;   

      Scanner keyboard = new Scanner(System.in);

      System.out.println("a) Count the number of vowels in the string.");
      System.out.println("b) Count the number of consonants in the string.");
      System.out.println("c) Count both the vowels and consonants in the string.");
      System.out.println("d) Enter another string.");
      System.out.println("e) Exit the program.");

      input = keyboard.nextLine();
      selection = input.charAt(0);

      while (Character.toLowerCase(selection) < 'a' || Character.toLowerCase(selection) > 'e')
      {
         System.out.print("Only enter a, b, c, d, or e: ");
         input = keyboard.nextLine();
         selection = input.charAt(0);
      }

      return selection;
   }
}
4

2 回答 2

3

看起来您正在初始化本地数组result,但随后尝试从成员数组中读取result。由于您尚未初始化成员之一,因此它仍然是null,因此java.lang.NullPointerException您正在看到。

您可能希望更改countVowelsAndCons为具有void返回类型,并摆脱本地result. 然后,您需要确保在尝试调用getNumVowels或之前调用它getNumConsonants。顺便说一句,像这样的东西index应该是成员函数中的局部变量——它们不属于类范围。

但更重要的是,这可能甚至不应该是一个类。你可能想要这样的东西:

private static boolean isVowel(char c)
{
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}

public static int countConsonants(String s)
{
    int count = 0;
    for(int i=0, len=s.length(); i<len; ++i)
    {
        if(!isVowel(s.charAt(i))) ++count;
    }
    return count;
}

public static int countVowels(String s)
{
    int count = 0;
    for(int i=0, len=s.length(); i<len; ++i)
    {
        if(isVowel(s.charAt(i))) ++count;
    }
    return count;
}
于 2012-05-12T15:51:17.080 回答
0

您得到 aNullPointerException因为您没有初始化实例变量result

我建议使用以下内容:

public class VowelCons {
    private final String str;
    private final int totalConsonants;
    private final int totalVowels;

    public VowelCons(final String s) {
        this.str = s;
        int totalConsonants = 0;
        int totalVowels = 0;
        if (null != s) {
            for (final char c : s.toCharArray()) {
                switch (c) {
                    case 'A':
                    case 'a':
                    case 'E':
                    case 'e':
                    case 'I':
                    case 'i':
                    case 'O':
                    case 'o':
                    case 'U':
                    case 'u':
                        totalVowels++;
                        break;
                    default:
                        if (Character.isAlphabetic(c)) {
                            totalConsonants++;
                        }
                        break;
                }
            }
        }
        this.totalConsonants = totalConsonants;
        this.totalVowels = totalVowels;
    }

    public String getString() {
        return str;
    }

    public int getTotalConsonants() {
        return this.totalConsonants;
    }

    public int getTotalVowels() {
        return this.totalConsonants;
    }

    public String toString() {
        return (null == str ? "" : str) + " [consonants=" + totalConsonants + ", vowels=" + totalVowels + "]";
    }

    public static void main(final String[] args) {
        for (final String arg : args) {
            final VowelCons vc = new VowelCons(arg);
            System.out.println(vc.toString());
        }
    }
}

例如,这将输出:

$ java VowelCons foo BaR "Lady GODIVA"
foo [consonants=1, vowels=2]
BaR [consonants=2, vowels=1]
Lady GODIVA [consonants=6, vowels=4]

以下是此示例应该可以帮助您学习的一些要点:

  1. 局部变量可以隐藏实例变量(参见[1][2])。
  2. 用于this引用实例变量(参见[1])。您应该始终使用 引用实例变量this,这可以防止在您将来进行代码更改时意外隐藏它,并允许 IDE 提供仅包含实例成员的上下文敏感建议。
  3. null String传递给构造函数的句柄。
  4. 用于switch简化逻辑,减少逻辑中的冗余代码if-else
  5. 检查小写和大写元音。
  6. 忽略元音/辅音计数中的非字母字符。
  7. 实现一个自定义toString().
于 2012-05-12T16:51:29.257 回答