【问题标题】:Adding to an object array list using a file reader使用文件阅读器添加到对象数组列表
【发布时间】:2014-04-25 23:24:57
【问题描述】:

基本上,在这种情况下,我必须让类相互交互,一个公司和一个驱动程序,这段代码是写在驱动程序中的。所以我使用文件阅读器来扫描一个看起来像这样的文本文件,每行之间有一个空格。

约翰:史密斯:制造:6.75:120:444

贝蒂:怀特:经理:1200.00:111

Stan:Slimy:Sales:10000.00:332

贝蒂:Boop:设计:12.50:50:244

代码如下。 company 类的 addEmployee 方法有一个 (string, string, string, double, int, int) 参数。它读取的文本文件在每个部分之间都有一个冒号,所以我可以将它添加到对象的数组列表中。并继续阅读,直到所有这些都被阅读。抱歉,如果我的问题难以理解,如果您想让我详细说明,请在 cmets 中告诉我。我只是不想让这个问题太长。

else if (e.getSource()==readButton){
            JFileChooser fileChooser = new JFileChooser("src");
        if  (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
        {
            empFile=fileChooser.getSelectedFile();
        }
            Scanner scan = new Scanner("empFile");
            while(scan.hasNext()){
                scan.next().split(":");
                if (position.equals("Manager")){
                    c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), 0, Integer.parseInt(empNum2));
                }
                else if(position.equals("Sales")){
                    c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), 0, Integer.parseInt(empNum2));
                }
                else{
                    c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), Integer.parseInt(secondParam2), Integer.parseInt(empNum2));
                }
            }

【问题讨论】:

  • 你有什么问题?
  • c 是什么,在您的情况下 employee 是什么?

标签: java arraylist delimiter filereader


【解决方案1】:

这一行:

scan.next().split(":");

将返回一个您没有存储在任何地方的Strings 数组。把它变成:

String[] rowData = scan.next().split(":");

并根据需要使用数组中的每个项目,例如填充变量或直接作为类构造函数的参数。提供前者的样本:

fName = rowData[0];
lName = rowData[1];
position = rowData[2];
firstParam2 = rowData[3];
secondParam2 = rowData[4];
empNum2 = rowData[5];

【讨论】:

  • 谢谢,我想这正是我所需要的。感谢您的快速回复。顺便说一句,您在数组中跳过了 4...
  • @user3530205 如果这是您正在寻找的答案,请不要忘记mark this post as an answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
  • 2012-08-02
  • 1970-01-01
  • 2018-05-16
  • 2012-06-10
  • 2017-07-14
  • 2011-12-05
相关资源
最近更新 更多