gpt4 book ai didi

java - 使用扫描仪读取文件

转载 作者:行者123 更新时间:2023-11-30 07:50:56 25 4
gpt4 key购买 nike

我在从文本文件 (amazon.txt) 中读取一行时遇到问题:

Boek(book)类的TextFile和读取方法:

   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);

}

这是我从类目录中读取的方法,它将第一个标记读取为类型,然后将扫描器发送到上面的类 Boek 中读取的方法。(类目录保存书籍的数组列表并从文件中读取,因此尚未完成)但我似乎无法从文件中读取文本的第一行,因为我陷入了19.95,必须将其读取为 ,但将 (19.95BOEK Dan Brown) 读作一个 token 。有什么技巧可以将 19.95 读作一个 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;

}

最佳答案

显然扫描仪读取越过线路。因此,您可以做的是首先读取单独的行,然后解析该行的字段。

    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();
}

此外,我在 Book.read() 中做了一个小小的更改:

long tkPrijs = sc.nextLong();

更改为:

double tkPrijs = sc.nextDouble();

然后运行:

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

关于java - 使用扫描仪读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33351843/

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