r/javahelp • u/Madridi77 • 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.
public static void golds(String[] countryArray) {
//int count = 0;
String currentCountry = new String();
for (int i = 0; i < countryArray.length; i++) {
currentCountry = countryArray[i];
int count = 0;
for (int j = 0; j < countryArray.length; j++) {
if (countryArray[j] != null) {
if (currentCountry.equals(countryArray[j])) { // FIX THE NULL POINTER ERROR!!!!!!!!!
count++;
}
}
else {
j = countryArray.length;
}
}
}
countryArray = removeDuplicates(countryArray);
System.out.println("Count of gold medalists by country:");
for (int g = 0; g < countryArray.length; g++) {
System.out.println(countryArray[g]);
}
2
u/lbkulinski Jun 08 '19
Did you initialize the elements of your array? They are
nullby default, which would be whycurrentCountryisnull.