I have to make a program that will ask for the user to enter 10 names, then sort the names alphabetically, then print each name, how many characters, and how many vowels.
I think I am close but keep getting this error in processing. Can anyone help with this?
`Exception in thread "Animation Thread" java.lang.NullPointerException
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1217)
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1211)
at java.lang.String.compareToIgnoreCase(String.java:1258)
at test.setup(test.java:35)
at processing.core.PApplet.handleDraw(PApplet.java:2117)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:193)
at processing.core.PApplet.run(PApplet.java:2020)
at java.lang.Thread.run(Thread.java:662)`
My code is:
import javax.swing.*;
String names[] = new String[10];
String temp;
String nameInput;
int length;
int vowel = 0;
char ch;
length = 0;
// store user input to array
for (int i = 0; i < names.length; i++) {
nameInput = JOptionPane.showInputDialog ("Enter a name:");
names[i] = nameInput;
length = names[i].length();
// sort into alphabetical order
for (int j = 0; j < names.length - 1; j++) {
for (int k = j + 1; k < names.length; k++) {
if (names[j].compareToIgnoreCase(names[k]) > 0) {
temp = names[j];
names[j] = names[k];
names[k] = temp;
}
}
}
// count vowels
char[] characters = nameInput.toCharArray();
for (int m = 0; m < characters.length; m++) {
ch = nameInput.charAt(m);
if ((ch == 'A') || (ch == 'a')
|| (ch == 'E') || (ch == 'e')
|| (ch == 'I') || (ch == 'i')
|| (ch == 'O') || (ch == 'o')
|| (ch == 'U') || (ch == 'u')) {
vowel++;
}
}
System.out.println("Name: " + names[i] + ", Length: " + length + ", Vowels: " + vowel);
vowel = 0;
}
This is the problem:
You’re trying to sort in the same loop that you’re entering the names.
So after entering the first name, the first element will be non-null, but all the other array elements will be null references, which is what’s causing the problem.
I suggest you split this into two separate loops:
Basically, you need to close your first loop earlier: