简体   繁体   中英

Cannot read text file into array and write to text file again

This my whole code. I want to make a simple program that will read a text file and put it to array then write it to the same text file, also can add and delete the existing input and my input.

Problem

The delete and writer part seems not working, only blank text file when I run the code

These are the error after I select the exit.

 java.lang.NullPointerException at ContactList.writer(ContactList.java:51) at 
ContactListDriver.main(ContactListDriver.java:73) at 
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at 
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at 
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at 
java.lang.reflect.Method.invoke(Unknown Source) at 
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:27‌​2)






public class Contact {

    //Each contact stores the name, phone number, and email address
    private String name;
    private String number;
    private String email;
    public Contact(String name, String number, String email)
    {
        this.name = name;
        this.number = number;
        this.email = email;
    }   
    public String getName()
    {
        return name;
    }
    public String getNumber()
    {
        return number;
    }

    public String getEmail()
    {
        return email;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setNumber(String number)
    {
        this.number = number;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

}

class for processing the inputs.

 import java.io.*;
 import java.lang.*;
 import java.util.*;


public class ContactList {

    public Contact[] myContacts;
    public static final int MAX = 100;
    private int numContacts;

    public ContactList()
    {
        myContacts = new Contact[MAX];
        numContacts = 0;
    }

    public void addContact(String name, String number, String email)
    {
        Contact c = new Contact(name, number, email);
        myContacts[numContacts] = c;
        numContacts++;
    }

    public void deleteContact(String name)
    {
      for ( int i = 0; i <= numContacts-1 ; i++){
        if(  name == myContacts[i].getName())
        {
         myContacts[i] = null;
           break; 
        }
      }
      numContacts--;   
    } 





  public void writer(){

      String x = "MyContacts.txt";
      try {
   PrintWriter outputs = new PrintWriter(x);

       for( int i=0; i < myContacts.length; i++)
         {

          Contact c = myContacts[i];
              if(c!=null){ // check if c is null before writing to file
                 outputs.println(""+c.getName()+" "+c.getNumber()+" "+c.getName());
                 outputs.flush();
            }

      }

          outputs.close();

    }catch (IOException e) {
     e.printStackTrace();


  } 
  catch(NullPointerException ex){
  }

  }


    public void displayContacts()
    {
        int i;
        for(i=0; i < myContacts.length; i++)
        {
            Contact c = myContacts[i];

            if(null != c){
            System.out.println("Name: " + c.getName());
            System.out.println("Number: " + c.getNumber());
            System.out.println("Email: " + c.getEmail());
            System.out.println("------------------------------------");

             }
        }
    }



}



    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

The Driver....

public class ContactListDriver {    
    public static void main(String[] args) throws FileNotFoundException
    {
        ContactList cList = new ContactList();
        File in = new File("MyContacts.txt");
        Scanner sc = new Scanner(in);
        int option;
        char again = 'n';

        String name = null;
        String number = null;
        String email = null;


        while(sc.hasNext())
        {
            //read one line from text file
            String entry = sc.nextLine();
            //System.out.println(entry);
            String[] con = entry.split("\\s+");
            //System.out.println(con[0] + " " + con[1] + " " + con[2]);
            cList.addContact(con[0], con[1], con[2]);
        }

        Scanner userIn = new Scanner(System.in);


        do{
            displayOptions();     
            option = userIn.nextInt();


            switch(option)
            {
                case 1:


                    System.out.println(" Name > ");
                    name = userIn.next();

                    System.out.println(" Number > ");
                    number = userIn.next();

                    System.out.println(" Email Address > ");
                    email = userIn.next();

                    cList.addContact(name, number, email);
                    break;
                case 2:
                    //delete contact
                    System.out.println("Contact Name > ");
                    name = userIn.next(); 
                    cList.deleteContact(name);
                    break;
                case 3:
                    //display contact
                    cList.displayContacts();
                    break;
                case 4:
                  cList.writer();
                  System.out.println(" are you sure ? press y ");
                  String x = userIn.next();
                  again = x.charAt(0);

                    break;
            }



        }while( again == 'n' );  



    }

    private static void displayOptions() {
        System.out.println("(1) Add");
        System.out.println("(2) Delete");
        System.out.println("(3) Show Contacts");
        System.out.println("(4) Exit");
    }




}

You have declared and initialized the Contact array of size MAX. but,it seems to be that you haven't initialized the elements though. ie c is null in the below code

 Contact c = myContacts[i];
                outputs.println(""+c.getName()+" "+c.getNumber()+" "+c.getName());
                outputs.flush();

myContacts[i] should return a Contact instance. As said by Meno , there are lot of other problems in your code. You have to always cover all the possible scenarios while writing the code.

There are many issues with your code so not easy to say where to begin.

First: Your public void deleteContact(String name) -method is broken. It compares Strings using == instead of equals(). And worse: It creates null pointers mid in your array which will cause problems in your writer()-method.

Second: Why do you use arrays? You should use java.util.ArrayList which offers out-of-the-box implementations for adding, getting and deleting contacts.

Third: If you are missing your text file, you might have overlooked it because of missing path so you don't know where to look for this file. So please add a full path to file name.

Fourth: I would also use scanner.hasNextLine() instead of scanner.hasNext() if you then call scanner.nextLine().

Since you said you are not allowed to use ArrayList you should study its source code especially for removing elements. It does not only nullify the array bucket, but also to shift all following elements one index backwards so you don't have any null gap until the index given by element count. And two breaks in deleteContact()-method are really not necessary.

One problem I see is:

You have a extra break; statement inside deleteContact(String name) function

and String comparision name == myContacts[i].getName() should be name.equals(myContacts[i].getName())

 public void deleteContact(String name)
        {
          for ( int i = 0; i <= numContacts-1; i++){
            if(  name.equals( myContacts[i].getName()))// string comparison uses equals();
            {
             myContacts[i] = null;
                numContacts--;  // this line should be inside of if condition 
               break; 
            }
            // break; No need of breaking the loop here
          }
        }

Another problem is at writer() function

public void writer(){

      String x = "MyContacts.txt";
      try {
   PrintWriter outputs = new PrintWriter(x);

       for( int i=0; i < myContacts.length; i++)
         {

          Contact c = myContacts[i];
              if(c!=null){ // check if c is null before writing to file
                 outputs.println(""+c.getName()+" "+c.getNumber()+" "+c.getName());
                 outputs.flush();
            }

      }

          outputs.close();

  }catch (IOException e) {
   e.printStackTrace();


} 
  catch(NullPointerException ex){ // Or just catch the NPE 
  }

Most importantly you need to fix the ContactList class. It is inserting new elements into the last index, and deleting at any location using the name .

For example, let's say the ContactList has three elements in it at 0, 1 and 2 indexes. So numContacts is set to 3.

Now ContactList has elements as:

[0]C0, [1]C1, [2]C2, [3]null, ...

Then if the contact at 0 index is deleted (set to null ), then numContacts is set to 2. Now the ContactList has elements as:

[0]null, [1]C1, [2]C2, [3] null, ...

A new insert will be added to the index 2, and it will override the C2 value.

Simplest solution is to use an ArrayList instead of an array.

As others have mentioned there are few more issues to fix, but above is the most important in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM