无法将文本文件读入数组并再次写入文本文件

时间:2013-12-30 10:06:46

标签: java

这是我的整个代码。 我想制作一个简单的程序来阅读 文本文件并将其放入数组然后将其写入 同一文本文件, 也可以添加和删除现有输入和我的输入。

问题

删除和编写器部分似乎不起作用,我运行代码时只有空白文本文件

选择退出后出现这些错误。

 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;
    }

}

用于处理输入的类。

 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;

司机......

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");
    }




}

4 个答案:

答案 0 :(得分:0)

您已声明并初始化了大小为MAX的Contact数组。但是,似乎你没有初始化元素。即以下代码中的c为空

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

myContacts[i]应返回Contact个实例。正如 Meno 所述,您的代码中还有很多其他问题。在编写代码时,您必须始终涵盖所有可能的场景。

答案 1 :(得分:0)

您的代码存在许多问题,因此不容易说明从哪里开始。

首先:您的public void deleteContact(String name) - 方法已损坏。它使用==而不是equals()来比较字符串。更糟糕的是:它会在数组中间创建空指针,这将导致您的writer() - 方法出现问题。

第二:为什么要使用数组?您应该使用java.util.ArrayList提供开箱即用的实施方式来添加,获取和删除联系人。

第三:如果你遗漏了你的文本文件,你可能会因为缺少路径而忽略它,所以你不知道在哪里寻找这个文件。所以请添加文件名的完整路径。

第四:如果你再调用scanner.nextLine(),我也会使用scanner.hasNextLine()代替scanner.hasNext()。

由于您说不允许使用ArrayList,因此您应该研究其源代码,尤其是删除元素。它不仅使数组桶无效,而且还将一个索引向后移动所有后续元素,因此在元素计数给出的索引之前没有任何空间隙。并且deleteContact() - 方法中的两个中断实际上没有必要。

答案 2 :(得分:0)

我看到的一个问题是:

break;函数

中有一个额外的deleteContact(String name)语句

String比较name == myContacts[i].getName()应为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
          }
        }

另一个问题是writer()功能

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 
  }

答案 3 :(得分:0)

最重要的是,您需要修复ContactList课程。它将新元素插入到最后一个索引中,并使用name在任意位置删除。

例如,假设ContactList在0,1和2索引中有三个元素。因此numContacts设置为3。

现在ContactList的元素为:

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

然后,如果0索引处的联系人被删除(设置为null),则numContacts将设置为2。 现在ContactList的元素为:

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

新的插入将添加到索引2,它将覆盖C2值。

最简单的解决方案是使用ArrayList而不是数组。

正如其他人所提到的,还有很多问题需要解决,但在我看来,上述内容是最重要的。