gpt4 book ai didi

java - 有没有办法使用扫描仪通过读取文件来构建一组对象?

转载 作者:行者123 更新时间:2023-12-02 09:28:07 25 4
gpt4 key购买 nike

我想知道是否有一种方法可以让扫描器读取java中的文件并将其编译成数组列表的对象,例如,如果正在读取的文件与workers属性的基本格式相同文件存在;姓名、薪资( float )、技能1( float )、技能2( float ),然后在引入新 worker 后再次重复。如;

文件“workers.txt”:

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

苏珊·内瑟斯兼职 7.50 份绘画.80雕刻.25

然后将其编译为具有给定属性的worker 1、worker 2、worker 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();
}
}
}

最佳答案

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

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

关于java - 有没有办法使用扫描仪通过读取文件来构建一组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com