English 中文(简体)
Un inthread “main” java.lang.NullPointerException-part2
原标题:Except in thread "main" java.lang.NullPointerException-part2

I 更改了我的代码,因为丹麦建议。 i 但现在可以编制方案,不管投入是什么,结果总是 2. i 将该方案的第二部分置于新的法典之下。 请提供帮助。

这里是新法典。

    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;
    }
}

there s another part of this program which gets the user s input and passes it to this class. Here s the code. [this part cannot be changed according to the regulations]

    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("
Number of vowels: " +
                        vc.getNumVowels());
                        break;
            case  b  :  System.out.println("
Number of consonants: " +
                        vc.getNumConsonants());
                        break;
            case  c  :  System.out.println("
Number 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;
   }
}
最佳回答

You re getting a NullPointerException because you are not initializing the instance variable 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. Local variables may hide instance variables (see [1] and [2]).
  2. Use this to reference instance variables (see [1]). You should always reference instance variables using this, which prevents accidentally hiding it when you make future code changes and allows IDEs to provide context sensitive suggestions that only contain instance members.
  3. Handle null Strings passed to the constructor.
  4. Use switch to simplify the logic and reduce redundant code in if-else logic.
  5. Check for lower-case and upper-case vowels.
  6. Ignore non-alphabetic characters in the vowel/consonant counts.
  7. Implement a custom toString().
问题回答

它像你一样,在开始使用地方阵列<>result,但随后试图从成员阵列读到result。 由于您先入选该成员,该成员仍然有<代码>null,因此,见到<代码>java.lang.NullPointerException。

也许希望修改<代码>countVowelsAndCons,以备有,避免的返回类型,并删除当地<代码>result。 然后,你需要确保在试图打上<条码>、植被NumVowels或<条码>。 顺便提一句,例如<代码> 你们的成员职能中应该有当地变量,它们不属于班级范围。

但更重要的是,这甚至可能只是一个阶层。 你们可能想要的是:

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;
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签