gpt4 book ai didi

java - 我如何使用trim()方法来完成这项工作?我需要读取txt文件,同时忽略空白行和以 "//"开头的行

转载 作者:行者123 更新时间:2023-12-01 19:28:58 27 4
gpt4 key购买 nike

public void readToooooolData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
scanner.useDelimiter("( *, *)|(\\s*,\\s*)|(\r\n)|(\n)");

while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!line.startsWith("//") || !(scanner.nextLine().startsWith(" ") )) {
String toolName = scanner.next();
String itemCode = scanner.next();
int timesBorrowed = scanner.nextInt();
boolean onLoan = scanner.nextBoolean();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
storeTool( new Tool(toolName, itemCode, timesBorrowed, onLoan, cost, weight) );
scanner.nextLine();
}
scanner.close();

}

}

txt 文件:

// this is a comment, any lines that start with //
// (and blank lines) should be ignored

// data is toolName, toolCode, timesBorrowed, onLoan, cost, weight
Makita BHP452RFWX,RD2001, 12 ,false,14995,1800
Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
Bosch GSR10.8-Li Drill Driver,RD3021,25, true,9995,820
Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400

最佳答案

您的代码存在一些问题。

  • 最好使用 try with resources打开扫描仪

  • 您指定的某些分隔符是重复的,有些是不必要的。空间包含在 \s 中,所以(\s*,\s*)( *, *) 的重复项,和(\r\n)|(\n)不需要。

  • 您从文件中读取一行并测试是否为注释或空行 - 好的。然后你需要从已经读取的行中提取 token ,但你不能使用 scanner.next()为此,因为它会在您刚刚阅读的行之后检索下一个标记。因此,您的代码实际上所做的是尝试解析非注释/非空行之后行上的信息。

  • 还有另一个scanner.nextLine()在循环末尾,因此您可以从文件中再跳过一行。

public void readToooooolData(String fileName) throws FileNotFoundException {
File dataFile = new File(fileName);
try (Scanner scanner = new Scanner(dataFile)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (line.startsWith("//") || line.isEmpty()) {
continue;
}
String tokens[] = line.split("\\s*,\\s*");
if (tokens.length != 6) {
throw new RuntimeException("Wrong data file format");
}
String toolName = tokens[0];
String itemCode = tokens[1];
int timesBorrowed = Integer.parseInt(tokens[2]);
boolean onLoan = Boolean.parseBoolean(tokens[3]);
int cost = Integer.parseInt(tokens[4]);
int weight = Integer.parseInt(tokens[5]);
storeTool( new Tool(toolName, itemCode, timesBorrowed, onLoan, cost, weight) );
}
}
}

关于java - 我如何使用trim()方法来完成这项工作?我需要读取txt文件,同时忽略空白行和以 "//"开头的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60379507/

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