0

I am having trouble finishing this code about counting the number of vowels and consonants in a string. When ever I send a string over to the class both getVowelCount method and getConstCount method turn out to be an error I believe the problem is in the for loop of both methods where I try and to call the isLetter method with the certain character of the string but I am not sure. I get

Exception in thread "main" java.lang.NullPointerException / at DCMvowelsAndConsonants.getVowelCount(DCMvowelsAndConsonants.java:30) / at DCMvowelsAndConsonantsDriver.main(DCMvowelsAndConsonantsDriver.java:40)

I'm not sure if i should post the driver since this is already big.

public class DCMvowelsAndConsonants
{
   String line;

   public DCMvowelsAndConsonants()
   {
      String line = " ";
   }

   public DCMvowelsAndConsonants(String l)
   {
      String line = l;
   }

   public static boolean isLetter(char i)
   {
      return i == 'a' || i == 'A' || i == 'e' || i == 'E' || i == 'i' || i == 'I' || i == 'o' || i == 'O' || i == 'u' || i == 'U';
   }

   public int getVowelCount()
   {
      int vowelCount = 0;

      for(int i = 0; i < line.length(); i++)
      {
         if(isLetter(line.charAt(i)))
            vowelCount++;
      }
      return vowelCount;
   }

   public int getConstCount()
   {
      int constCount = 0;

      for(int i = 0; i < line.length(); i++)
      {
         if(!isLetter(line.charAt(i)))
            constCount++;
      }
      return constCount;
  }
}

2 Answers2

4

Change your constructors to remove the "String " part. That is declaring a local variable and assigning to that, instead of assigning to your member variable.

So they should look like:

   public DCMvowelsAndConsonants()
   {
      line = " ";
   }

   public DCMvowelsAndConsonants(String l)
   {
      line = l;
   }
Buddy
  • 10,874
  • 5
  • 41
  • 58
0

Your problem is with your constructors. You are creating a new variable in the constructor. Replace your constructors as:

public DCMvowelsAndConsonants() {
      this.line = " ";
}

public DCMvowelsAndConsonants(String l) {
      this.line = l;
}
Srikanth K
  • 99
  • 1
  • 1
  • 7