有没有一种方法可以使用扫描仪通过读取文件来构建一组对象?

时间:2019-10-01 15:31:58

标签: java arrays object

我想知道是否有一种方法可以让扫描程序读取java中的文件并将其编译为arraylist的对象,例如,正在读取的文件是否具有与worker属性相同的基本格式。文件存在名称,工资率(浮动),技能1(浮动),技能2(浮动),然后在引入新工人后再次重复。例如;

文件“ workers.txt”:

鲍勃溢出 全日制12.50 phr 绘画.45 雕刻.85

苏珊·纳索斯(Susan Nasus) 兼职7.50份 绘画.80 雕刻.25

然后将其编译为具有给定属性的工作程序1,工作程序2,工作程序3等到数组中。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RaceCarOne
{
        public static void main(String args[]) throws FileNotFoundException 
        {
            //creating File instance to reference text file in Java
            File text = new File("C:\\Users\\jayli\\Desktop\\Workers.txt");
            //Creating Scanner instance to read File in Java
            Scanner s = new Scanner(text);
            //Reading each line of file using Scanner class
            int lineNumber = 1;
            while(s.hasNextLine())
            {
                String line = s.nextLine();
                System.out.println("line " + lineNumber + " :" + line);
                lineNumber++;
            }          
            s.close();  
        }   
}

class Worker 
{
    File text = new File("C:\\Users\\jayli\\Desktop\\Workers.txt");

    Scanner s = new Scanner(text);

    String Name;
    int WorkHours;
    int Fab;
    int Serv;
    int Diag;
    int Trans;
    int Intake;
    int BW;
    int Paint;
    boolean working = false;

    Worker(String workername, float pay, float Fab, float Serv, float Diag, float Trans, float Intake, float BW, float Paint)
    {
        while(s.hasNextLine())
        {

        workername = s.nextLine();
        pay = s.nextInt();
        Fab = s.nextInt();
        Serv = s.nextInt();
        Diag = s.nextInt();
        Trans = s.nextInt();
        Intake = s.nextInt();
        BW = s.nextInt();
        Paint = s.nextInt();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我建议使用s.nextline()获取一行,然后根据您的意愿进行拆分。您可以为此使用正则表达式模式,例如可以使用Regexr进行测试。另外,您可以使用split()方法并按空格分割。但是,由于这会引发其他问题(例如,名称中带有空格的技能),因此我同意Sweeper的观点,即您可能应使用JSON之类的内容作为输入。

此外,我认为您的Worker构造函数只会循环遍历整个文件,并且每次都会在最后一行显示信息。