Reputation: 588
I am having trouble reading a line from a text file (amazon.txt):
TextFile and read method of Class Boek(book) :
BOEK Harry Mulisch, De Aanslag, 9023466349, Bezige Bij, 246, 2010, 19.95
BOEK Dan Brown, De Da Vinci Code, 9024562287, Luitingh, 432, 2009, 12.49
CD Foo Figthters, Wasting Light, 0886978449320, Sony, 2011, 11.95
MP3 Hooverphonic, Reflection, 0888837802826, Sony, 2013, 15.00, 165
public static Boek read(Scanner sc){
sc.useDelimiter(", ");
String tkArtiest = sc.next();
String tkTitel = sc.next();
long tkISBN = sc.nextLong();
String tkUitgever = sc.next();
int tkAantalBladzijden = sc.nextInt();
int tkJaarUitgave = sc.nextInt();
long tkPrijs = sc.nextLong();
return new Boek(tkArtiest, tkTitel, tkISBN, tkUitgever, tkAantalBladzijden, tkJaarUitgave, 0);
}
This is my read method from Class catalog which reads the first token as a type and then sends the scanner to method read in Class Boek above. (Class catalog keeps an arraylist of books and reads from file, hence it is not finished) But I can't seem to read the first line of text from my file because I get stuck at 19.95 which must be read as a long, but reads (19.95BOEK Dan Brown) as one token. Any tricks to read 19.95 as a one token??
public static Catalogus read(File inFile) {
Catalogus catalog = new Catalogus();
try {
Scanner sc= new Scanner(inFile);
String type = sc.next();
if (type.equals("BOEK")) {
catalog.addEntertainment((Boek.read(sc)));
} else {
System.out.println("type != BOEK or ERROR");
}
} catch (FileNotFoundException e) {
System.out.print("Problem reading file.");
e.printStackTrace();
}
return catalog;
}
Upvotes: 1
Views: 142
Reputation: 1744
Apparently scanner
reads across the line. So what you could do is first read an individual line, then parse the fields of that line.
try {
Scanner sc= new Scanner(inFile);
sc.useDelimiter( System.getProperty("line.separator") );
while (sc.hasNext()) {
String line = sc.next();
System.out.println(line);
Scanner scanline = new Scanner(line);
String type = scanline.next();
if (type.equals("BOEK")) {
catalog.addEntertainment((Boek.read(scanline)));
} else {
System.out.println("type != BOEK or ERROR");
}
}
} catch (FileNotFoundException e) {
System.out.print("Problem reading file.");
e.printStackTrace();
}
Furthermore I made a minor change in Book.read()
:
long tkPrijs = sc.nextLong();
Change to:
double tkPrijs = sc.nextDouble();
And run:
BOEK Harry Mulisch, De Aanslag, 9023466349, Bezige Bij, 246, 2010, 19.95
addEntertainment() added this Boek to Catalogue
BOEK Dan Brown, De Da Vinci Code, 9024562287, Luitingh, 432, 2009, 12.49
addEntertainment() added this Boek to Catalogue
CD Foo Figthters, Wasting Light, 0886978449320, Sony, 2011, 11.95
type != BOEK or ERROR
MP3 Hooverphonic, Reflection, 0888837802826, Sony, 2013, 15.00, 165
type != BOEK or ERROR
Upvotes: 1