有一个文本文件cost.txt,里面存放数据如下: 电脑,6400元/台 电视机,3689元/台 冰箱,7569元/台 书桌,3376元/台 手机,7735元/台 请用Scanner类和正则表达式解析出文件中的价格,计算总额,并在控制台输出。
时间: 2023-08-16 14:09:37 浏览: 133
好的,我可以为您编写代码来解析出价格并计算总额。以下是代码示例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PriceParser {
public static void main(String[] args) {
File file = new File("cost.txt");
double totalCost = 0.0;
try {
Scanner scanner = new Scanner(file);
Pattern pattern = Pattern.compile("(\\d+)元/台");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
double price = Double.parseDouble(matcher.group(1));
totalCost += price;
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("总价为:" + totalCost + "元");
}
}
```
解析过程解释:
1. 创建一个File对象,用于读取文件。
2. 创建一个变量totalCost,用于累计总价。
3. 使用Scanner类读取文件。
4. 创建一个正则表达式模式,用于匹配价格。
5. 逐行读取文件内容。
6. 对于每一行内容,用正则表达式匹配价格。
7. 如果匹配成功,将价格加入总价中。
8. 关闭Scanner类。
9. 输出总价。
请注意,此代码假定文件中的每一行都包含一个价格。如果文件格式不正确,可能会抛出异常。
阅读全文
相关推荐














