Reputation: 1
I was wondering if there was a way to have a scanner read through a file in java and compile it into an object of an arraylist, for example if the file being read is in the same basic format of a workers attributes in the file being; Name, Payrate(float), skills 1(float), skills 2(float), then have it repeat again after a new worker is introduced. Such as;
file "workers.txt":
Bob Overflow Full-time 12.50 phr Painting .45 carving .85
Susan Nasus part-time 7.50 phr painting .80 carving .25
then compile it to be worker 1, worker 2, worker 3 ect with the given attributes into an array.
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();
}
}
}
Upvotes: 0
Views: 38
Reputation: 118
I suggest using the s.nextline() to get a line, and then split it according to your wishes. You could use a regex pattern for this which you can test with Regexr for example. Alternatively you can use the split()-Method and split by spaces. However, as this invokes other problems (e.g. skills with spaces in their name), I agree with Sweeper in that you should probably use something like JSON for your input.
Additionally, I think your constructor for Worker just loops through the whole file and you end up with the info on the last line everytime.
Upvotes: 1