除了线程“main”java.lang.NullPointerException-part2之外

时间:2012-05-12 15:48:24

标签: java nullpointerexception

我改变了我的代码,如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;
   }
}

2 个答案:

答案 0 :(得分:3)

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

您可能希望将countVowelsAndCons更改为void返回类型,并删除本地result。然后,您需要确保在尝试拨打getNumVowelsgetNumConsonants之前致电它。顺便提一下,像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;
}

答案 1 :(得分:0)

您收到NullPointerException,因为您没有初始化实例变量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()