是否可以使用扫描仪通过读取文件来构建一组对象?

问题描述 投票:0回答:1

我想知道是否有一种方法可以让扫描程序读取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();
        }
    }
}
java arrays object
1个回答
1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.