-1

This program is a small contact manager. I am having a problem calling the sortContacts method. It gives me a nullpointerexception every time I call the method. I am trying to have the method sort the contacts from A-Z but for some reason the arrays appear to be empty? The text file they are loaded from in loadContacts has entries in it, and prints perfectly fine (with the index number) when displayContacts is called.

I have tried using ArrayLists to no avail. It just seems like comparing strings inside arrays will just never work?

Exception in thread "main" java.lang.NullPointerException
    at Contacts.sortContacts(Contacts.java:179)
    at Contacts.menu(Contacts.java:47)
    at Contacts.main(Contacts.java:25)



import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Contacts {
    //global variables
    public static int counter = 0;
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static int x;
    static String[] name = new String[101];  
    static String[] number = new String[101];

public static void main(String[] args) throws IOException {//main method, sends user to the menu method
   menu();
}
//The menu method displays the option menu and compares user input to a menu option
public static void menu() throws IOException{
    int choice = -1;        
    while (choice != 7){        
        System.out.println("Main Menu");
        System.out.println("1. View all Contacts\n2. Add Entry\n3. Modify Entry\n4. Delete Entry\n5. Save\n6. Load\n7. Sort Conacts\n8. Exit");        
        choice = Integer.valueOf(in.readLine()).intValue();        
            switch(choice){       
                case 1: displayContacts();
                    break;
                case 2: addContact();
                    break;
                case 3: modifyContact();
                    break;
                case 4: deleteContact();
                    break;
                case 5: saveContact();
                    break;
                case 6: loadContact();
                    break;
                case 7: sortContacts(name);
                    break;
                default:System.exit(0);//terminates the program (quit)   
             } 
     }  
}
private static void displayContacts() throws IOException {  
    System.out.println(counter);
    for(int i = 0; i < counter; i++){
        if(name != null) {//this loops prevents the program from printing out empty contact slots
            System.out.println("Contact " + i + ": " + name[i] + " | " + number[i]);        
        }
        else{
            System.out.print("");
        }                   
    }
}
public static void addContact() throws IOException {  
    //check the counter variable
    int print;
    BufferedReader scan = new BufferedReader(new FileReader("contacts.txt"));
    print = Integer.valueOf(scan.readLine()).intValue();
    print = counter;

    if (counter < 101){ 
        //prompt the user for information
        System.out.println("Enter the Contact's name:");
        name[counter] = in.readLine();
        System.out.println("Enter the Contact's number");
        number[counter] = in.readLine();        
        //increment the counter
        counter++;
    } else {
        System.out.println("Sorry the array is full!");
    }   
    scan.close();
}
public static void modifyContact() throws IOException{
    boolean found = false;
    int flag = 0;
    String modCon;
    System.out.println("Enter the name of the contact you wish to modify:");
    modCon = in.readLine(); 
    for (int i = 0; i < counter; i++){    
        if (modCon.compareTo(name[i]) == 0){
            flag = i;
            found = true;
        }
       }
     if (found == false){
            System.out.println("Item not found");
        }
     else{
         System.out.println("Contact found!");
         System.out.println("Enter new name: ");
         name[flag] = in.readLine();
         System.out.println("Enter new number: ");
         number[flag] = in.readLine(); 
     } 
 }
private static void deleteContact() throws IOException {
    boolean found = false; 
    int flag = -1;
    String delCon; 
    System.out.println("Enter the name of the contact you wish to delete:");
    delCon = in.readLine(); 
    for(int i = 0; i < counter; i++){
        if(delCon.compareTo(name[i]) == 0) {
            flag = i;
            found = true;
            }
        }

    if(found == false){
        System.out.println("Item not found");
    }
    else{
        if (flag == counter - 1){
            name[flag] = "";
            number[flag] = "";
            counter--;
    } else{             
         for (int i = flag; i < counter; i++){
             name[i] = name[i + 1];
             number[i] = number[i + 1];         
         }
        }
    }
    counter = flag + 1;
}

public static void saveContact() throws IOException{
    //Create File output
    PrintWriter output;
    output = new PrintWriter(new FileWriter("contacts.txt"));
    //Output a header to the file, in this case it is the number of criminals
    output.println(counter);
    //loop through our array outputting to a file
    for(int i = 0; i < counter; i++){
        System.out.println("Writing Contact to file");
        output.println(name[i]);
        output.println(number[i]);
    }
    output.close();
} 
public static void loadContact() throws IOException {
    int print;
    BufferedReader in = new BufferedReader(new FileReader("contacts.txt"));
    print = Integer.valueOf(in.readLine()).intValue();
    counter = print; // tells the counter where to continue from (if loading a file)
    System.out.println("Loading " + print + " Contacts");    
    for (int i = 0; i < print; i++){
            //read in the data
            name[i] = in.readLine();
            number[i] = in.readLine();          
        }
     in.close();
     }

public static void sortContacts(String[] a) throws IOException{
    //counters i and j
    int i = 0;
    int j = 0;
    //"smallest" flag"
    int smallest = 0;
    //temporary holder for swapping
    String temp;
    //Selection Sort
    for (i = 0; i < 100; i++){
        smallest = i;       
        for (j = i; j < 10; j++){
            //compare the current smallest with the current array element
            if (name[j].compareTo(name[smallest]) < 0){
                smallest = j;
            }

            //swap the smallest
            temp = name[i];
            name[i] = name[smallest];
            name[smallest] = temp;
        }
    }

} 
}   
cloomx
  • 11
  • 3
  • Can you post the stack trace for the exception you're getting? it should say where the issue is. – F. Stephen Q Sep 01 '15 at 03:43
  • Have a look at the `java.util.Collections.sort()` methods. Also consider storing your contacts in a `Set`, rather than in a `List`. Maybe a `SortedSet` is appropriate? – Bex Sep 01 '15 at 04:23

1 Answers1

1

Read this to understand what your exception means: What is a NullPointerException, and how do I fix it?

In your case, if I pick case 7 in your menu, name is not initialized before you call sortContacts so every index is equal to null by default because it is a string array. So in sortContacts when you try something like name[j].compareTo(name[smallest] you get your null pointer exception because name[j] is equal to null.

To fix this you need to make sure that you populate your array with values from the file before you give the option to call sortContacts.

Community
  • 1
  • 1
Zarwan
  • 5,537
  • 4
  • 30
  • 48