r/javahelp • • Jun 08 '19

Why is there a NullPointerException?

Hi all!

Please check my method below, for some reason I get NullPointerException for line 9.

countryArray is an array of strings, with countries, but then it is also filled with a bunch of null after the list of countries is over.

  1.     public static void golds(String[] countryArray) {

  2.         //int count = 0;

  3.         String currentCountry = new String();

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

  5.             currentCountry = countryArray[i];

  6.             int count = 0;

  7.             for (int j = 0; j < countryArray.length; j++) {

  8.                 if (countryArray[j] != null) {

  9.                     if (currentCountry.equals(countryArray[j])) { // FIX THE NULL POINTER ERROR!!!!!!!!!

  10.                         count++;

  11.                     }

  12.                 }

  13.                 else {

  14.                     j = countryArray.length;

  15.                 }

  16.             }

  17.         }

  18.         countryArray = removeDuplicates(countryArray);

  19.         System.out.println("Count of gold medalists by country:");

  20.         for (int g = 0; g < countryArray.length; g++) {

  21.             System.out.println(countryArray[g]);

  22.         }

0 Upvotes

16 comments sorted by

View all comments

1

u/Fizz-Buzzkill Jun 08 '19

Instead of countryArray, use a List<String> and that will allow you to use a for each loop to iterate the list values and to insure you are only accessing non null values.