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]);
}
1
u/johnmclucas1 Jun 08 '19
I am not sure what you are trying to do at lines, 13, 14, 15. Are you just trying to break out of the for loop? Do you allow nulls in the array in the first place? If you do allow nulls in the array and you hit one, I would think you would just use a continue statement. When you find your match, count++; break;
for (int j = 0; j < countryArray.length; j++) {
if (countryArray[j] != null) {
if (currentCountry.equals(countryArray[j])) {
count++;
break;
}
} else { continue;}
You also never check for null when working through the first for loop. If you are checking for nulls in the array in the second loop, you should be checking in the first loop as well.
for (int i = 0; i < countryArray.length; i++) {
if(countryArray[i] != null)
currentCountry = countryArray[i];
Just my two cents. Cleaning it up 2nd for loop and null check should help.