For some reason whenever I test this, the IDE throws a NullPointerException at line 46 (the for loop that check the array for a name). It seems to work, since it fetches the name and returns it, but then immediately follows with the exception. Can anyone explain? Thanks!
import java.util.*; class PhoneNumbers {
private String name;
private String number;
PhoneNumbers(String n, String numb) {
this.name = n;
this.number = numb;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean repeat = true;
int count = 11;
PhoneNumbers[] contacts = new PhoneNumbers[30];
contacts[0] = new PhoneNumbers("Gina", "(847) 342-0912");
contacts[1] = new PhoneNumbers("Marcia", "(847) 341-2392");
contacts[2] = new PhoneNumbers("Rita", "(847) 354-0654");
contacts[3] = new PhoneNumbers("Jennifer", "(414) 234-0912");
contacts[4] = new PhoneNumbers("Fred", "(414) 435-0434");
contacts[5] = new PhoneNumbers("Neil", "(608) 123-0914");
contacts[6] = new PhoneNumbers("Judy", "(608) 123-0312");
contacts[7] = new PhoneNumbers("Arlene", "(608) 123-0312");
contacts[9] = new PhoneNumbers("LaWanda", "(920) 787-9813");
contacts[10] = new PhoneNumbers("Deepak", "(930) 412-0991");
while (repeat) {
boolean found = false;
System.out.print("Enter your friends name: ");
String nameInput = sc.nextLine();
if (!nameInput.equalsIgnoreCase("quit")){
for(int i = 0; i < count - 1; i++){
if (contacts[i].getName().equalsIgnoreCase(nameInput)) {<---Here's where the issue occurs***
found = true;
System.out.println(contacts[i].getName() + "'s number is " + contacts[i].getNumber());
}
}
if (!found){
System.out.println("Enter your friends phone number: ");
String num = sc.nextLine();
contacts[count + 1] = new PhoneNumbers(nameInput, num);
count++;
}
}else if (nameInput.equalsIgnoreCase("quit")) {
repeat = false;
}else if (count == 30){
repeat = false;
}
}
}
}