简体   繁体   English

使用文件阅读器添加到对象数组列表

[英]Adding to an object array list using a file reader

Basically I have to classes interacting with one another in this situation one company and one the driver, this code is written in the driver. 基本上,在这种情况下,我必须与一类公司和一个驱动程序相互交互,这些代码是在驱动程序中编写的。 So I am using a file reader to scan a text file that looks like this with a space between each line. 因此,我正在使用文件读取器来扫描看起来像这样的文本文件,每行之间都有一个空格。

John:Smith:Manufacturing:6.75:120:444 约翰:史密斯:制造:6.75:120:444

Betty:White:Manager:1200.00:111 贝蒂:白:经理:1200.00:111

Stan:Slimy:Sales:10000.00:332 Stan:Slimy:Sales:10000.00:332

Betty:Boop:Design:12.50:50:244 贝蒂:大桶:设计:12.50:50:244

And the code is as follows. 和代码如下。 The addEmployee method of the company class has a (string, string, string, double, int, int) parameter. 公司类的addEmployee方法具有(string,string,string,double,int,int)参数。 The text file it reads in has a colons inbetween each part, so howe can I add it to the arraylist of objects. 它读取的文本文件在每个部分之间都有一个冒号,因此如何将其添加到对象的数组列表中。 And keep going until all of them are read. 并继续进行下去,直到所有内容都被阅读为止。 Sorry if my questions difficult to understand, if you want me to elaborate let me know in the comments. 抱歉,如果我的问题难以理解,请让我详细说明。 I just didn't want to make the question too long. 我只是不想让这个问题太久。

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

This line: 这行:

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

Will return an array of String s that you're not storing anywhere. 将返回一个String数组,该数组不存储在任何地方。 Turn it into: 变成:

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

And use every item in the array as you wish, for example to fill your variables or directly as arguments for your class constructor. 并根据需要使用数组中的每个项目,例如,填充变量或直接将其用作类构造函数的参数。 Providing a sample of the former: 提供前者的样本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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