【问题标题】:How to Store Different Data from Text File into ArrayLists?如何将文本文件中的不同数据存储到 ArrayLists 中?
【发布时间】:2019-04-26 14:44:48
【问题描述】:

有人要求我以数组的形式创建员工电话簿,其中包含他们的姓名和分机号码。电话簿是支持几个功能的:

  1. 添加将按姓氏字母顺序插入的新条目

  2. 按名称或编号删除条目

  3. 查找名称给定名称

  4. 更改号码

  5. 打印整个电话簿

所以没有什么先进的,但是我遇到的问题在于文本文件和获取正确存储在数组中的信息。文本文件包含以下格式的制表符分隔的数据:

姓首字母扩展名

我相信从作业的措辞来看,我被要求首先将填充的文本文件数据加载到程序中的数组中,然后使用我之前提到的函数对其进行操作。他们明确表示这里不需要写回文件。

到目前为止,我已经创建了几个类,其中包含将在项目中使用的每个对象的一般信息(即 Entry 类、Directory 接口 [必需]、ArrayDirectory 类、DirectoryFile 类)。我正在尝试从文本文件中读取 3 个不同的项目,然后将其存储在我为其创建构造函数的 Entry 对象中。我知道我将如何使用这些方法,我只是无法在文本文件和我的数组之间创建这个初始链接,这意味着我根本无法取得进展。我已尝试实施在网上找到的解决方案,但事实证明这更令人困惑。

由于我将数据保存为自定义对象(条目),因此我在这里也遇到了问题,最终感到非常困惑。

入门类

public class Entry {

    private String firstName = null;
    private String surname = null;
    private String extension = null;

    public Entry(String firstName, String surname, String extension) {
        super();
        this.firstName = firstName;
        this.surname = surname;
        this.extension = extension;
    }

...(getters and setters, toString)...

ArrayDirectory 类

public class ArrayDirectory implements Directory {

    private final static int MAX_ENTRIES = 20;
    private static Scanner input = new Scanner(System.in);
    DirectoryFile file = new DirectoryFile("C:\\Users\\John\\Documents\\Phonebook.txt");
    static List<Entry> phonebook = new ArrayList<>(MAX_ENTRIES);

    public void addEntry() throws IOException {
        // check if phone book is empty before loading entries
        System.out.println(phonebook.isEmpty());
        loadEntries(file.getFile());
        System.out.println("Enter first name: ");
        String fname = input.nextLine();
        System.out.println("Enter second name: ");
        String sname = input.nextLine();
        System.out.println("Enter telephone extension: ");
        String telephone = input.nextLine();

        Entry entry = new Entry(fname, sname, telephone);
        phonebook.add(entry);
        System.out.println("Added staff member: \n" + fname + "\n" + sname + "\n" + telephone);
        System.out.println(Arrays.toString(phonebook.toArray()));

    }

    public String loadEntries(File file) throws IOException {
        String surname = null, fname = null, extension = null;
        BufferedReader br = new BufferedReader(new FileReader(file));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                String arr[] = line.split("\\s+");
                surname = arr[0];
                fname = arr[1];
                extension = arr[2];
                Entry entry = new Entry(surname, fname, extension);
                phonebook.add(entry);
                line = br.readLine();

            }
        } finally {
            br.close();
        }
        return null;
    }

...(other methods for functionality, testing etc.)...

目录文件类

public class DirectoryFile {

    private File file;

    public DirectoryFile(String fileName) {
        this.file = new File(fileName);
    }

    public DirectoryFile(File file) {
        this.file = file;
    }

    public File getFile() {
        return file;
    }

我遇到的问题是,在运行 loadEntries() 方法时,它会给出 OutOfBoundsException 并声明 index 1 out of bounds for length 1。我想我的方法的返回签名也可能不正确,但这让我更加困惑。我应该将电话簿 ArrayList 传递给方法而不是返回字符串吗?

对不起,这是我第一次在网上寻求帮助,如果我重复了自己,请见谅。

【问题讨论】:

    标签: java arrays file


    【解决方案1】:

    我现在没有太多时间,但这就是我为你所做的...... 修改您的 Entry 类以实现 Comparable 并像这样覆盖 equals():

    public class Entry implements Comparable {
    
            private String firstName = null;
            private String surname = null;
            private String extension = null;
    
            public Entry(String firstName, String surname, String extension) {
                this.firstName = firstName;
                this.surname = surname;
                this.extension = extension;
            }
    
            @Override
            public int compareTo(Object arg0) {//important for sorting
                this.surname.compareTo(((Entry) arg0).surname);
                return 0;
            }
    
            @Override
            public boolean equals(Object arg0) {//important for deleting
                return ((Entry) arg0).firstName.equalsIgnoreCase(this.firstName);
            }
        }
    

    以下是其他附加方法:

    
        public void writetofile(List<Entry> entry) throws Exception {
            File f = new File("path");
            try (Writer w = new FileWriter(f); PrintWriter pw = new PrintWriter(w);) {
                for (Entry e : entry) {
                    String line = e.surname + "--------" + e.firstName + "--------" + e.extension;
                    pw.println(line);
                }
            } catch (Exception e) {
                throw e;
            }
        }
    
        public List<Entry> sortbysurname(List<Entry> entry) {
            Collections.sort(entry);
            return entry;
        }
    
        // returns the index of the entry
        public boolean deleteByName(String name, List<Entry> entry) {
            return entry.remove(new Entry(name, "", ""));
        }
    

    【讨论】:

    • 不幸的是,我无法对其进行测试,希望它能正常工作。如果有任何挑战,请发表评论,并在安息日后照看一下
    • 感谢您的帮助。只是刚刚检查了该网站,因为没有收到电子邮件通知。你能检查一下我编辑过的帖子,看看你能不能用 loadEntries() 方法帮助我?我需要它从文本文件中加载所有数据并将每一行存储为一个条目对象并存储在电话簿 ArrayList 中。当我运行 loadEntries() 方法时,它给了我一个 OutOfBounds 异常错误,因为显然索引 1 超出了长度 1 的范围...?
    • 肯定是因为fname = arr[1]; 试图访问一个不可用的索引。 line.split("\\s+"); 中的条件仅返回大小为 1 的数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 2023-02-10
    • 1970-01-01
    • 2017-03-29
    • 2012-10-31
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多