-1

I have a 2d array of "#" and "." I am Passing into a method, I am then trying to iterate through the array and find how many "#" are in it. I keep getting a NULLPOINTER exception when using .equals. the method should return the amount of "#" in the array. I tried iterating through the 2d Array and then converted the 2d into a single dimension array and still am getting the EXCEPTION Im not sure what I am doing wrong, any help would be greatly appreciated. my code is:

public static int countSeats(String[][] aud){

   int openSeats = 0;

   String [] audit;
   audit = new String[120];

   int k = 0;
   for(int i= 0; i < aud.length; i++)
       for(int j = 0; j < aud[i].length; j++)
           audit[k++] = aud[i][j];

    for(int i= 0; i <= audit.length; i++){   
       openSeats = audit[i].equals("#")? +1:+0;
    }
return openSeats;

3 Answers3

2

You're getting an exception because of your loop condition:

for(int i= 0; i <= audit.length; i++){

Notice how you're using <= and not <. You're looping through the entire audit array, and then going one more than you should, resulting in the NullPointerException.

Jessie
  • 2,319
  • 1
  • 17
  • 32
  • Even after changing the sign to <, the exception is still being thrown. The compiler seems to be pointing to openSeats = audit[i].equals("#")? +1:+0; I was pretty certain this was a solid way of checking the contents of an array. each iteration should be returning a string which should be compared with "#" using the .equals method, but i must be totally missing something. – B_ant311 Feb 05 '17 at 03:11
  • If you want to increment the value either do `openSeats += audit[i].equals("#") ? 1 : 0;` or use an `if` and `openSeats++`. The NullPointer exception you're getting now is likely because `audit.length` is always 120, which is what you defined it as. You actually should check if `audit[i]` is null, since you will need to rely on that to know where your array ends. Otherwise you could use an ArrayList and not have to check for nulls yourself. – Jessie Feb 05 '17 at 04:01
0

The fact that you declare String[] audit, makes the solution even more complicated as you MAYBE TRY TO PUT ALL THE 2-D in 1-D thinking that it will simplify the problem for you, but it wont. Stay inside the 2-D, and do the search

   int openSeats = 0;
   for(int i= 0; i < aud.length; i++)
   {
       for(int j = 0; j < aud[i].length; j++)
       {
           if( aud[i][j].equals("#") )
           {
               openSeats++;
           }
       }
   }
   return openSeats; 
ShayHaned
  • 358
  • 3
  • 8
0

As others have pointed out, you are running your for loop one iteration extra by having i <= audit.length; instead of i < audit.length;. Also, as a good practice, always keep the String literal on the left side of the method call. E.g. instead of aud[i][j].equals("#"), do "#".equals(aud[i][j]) to avoid any possibility of NPE.

VHS
  • 9,534
  • 3
  • 19
  • 43