java - scanner.useDelimiter 不适用于基于 Web 的 CSV 文件
问题描述
所以我是Java的初学者,我很难学习,所以请放轻松。我正在研究一种解决方案,该解决方案将用户输入英国货币并找到用户输入国家/地区的汇率。不知道我是否走在正确的轨道上,但下面是用户输入要转换的货币金额和国家后的代码。我需要读取基于 Web 的 CSV 文件并解析为 POJO,但我无法让 in.useDelimiter 工作。
public static Double findExchangeRateAndConvert(String currencyType, double amount) throws IOException {
URL url = new URL("https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/842362/exrates-monthly-1119.csv");
try (var in = new Scanner(
new BufferedReader(
new InputStreamReader(url.openStream())))) {
var line = "";
in.useDelimiter(",");
while (in.hasNextLine()) {
line = in.nextLine();
System.out.println(line);
if (line.contains(currencyType)) {
System.out.println("I found it.");
System.exit(0);
}
}
}
return null;
}
解决方案
使用您的扫描仪一次读取一行,然后根据正则表达式拆分该行。逐行处理是一种很好的方法,因为它很容易理解正在发生的事情。
public class Main {
public static void main(String[] args) throws IOException {
Double d = Main.findExchangeRateAndConvert("USD", 12);
System.out.println("d=" + d);
}
public static Double findExchangeRateAndConvert(String currencyType, double amount) throws IOException {
URL url = new URL("https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/842362/exrates-monthly-1119.csv");
try (var in = new Scanner(
new BufferedReader(
new InputStreamReader(url.openStream())))) {
var line = "";
in.useDelimiter(",");
while (in.hasNextLine()) {
line = in.nextLine();
System.out.println(line);
String[] splitLine = line.split(",");
if (splitLine[2].equals(currencyType)) {
System.out.println("I found it.");
return Double.valueOf(splitLine[3]);
}
}
}
return null;
}
}
推荐阅读
- switch-statement - ifelse 预期的声明或声明
- php - 我是否正确使用了 file_get_contents?
- ios - 当设置为“全部链接”时,DependencyService.Get 返回 null
- ios - 无法将正确的信息从 tableview 传递到新的视图控制器
- javascript - NodeJS - 找不到 JSON 文件
- c++ - 尽管没有错误,openCL 内核仍返回垃圾值
- python - 我需要一些帮助来尝试对字符串列表进行排序,但在该列表的特定索引处
- typescript - 在节点中使用 Typescript 正确解析 GraphQL 模块
- c++ - 使用堆栈为下一个最大数编写代码时面临 SIGSEGV(分段错误)
- java - getBean() 是否应该延迟 bean 实例化?