java - 读取文件时搜索大于 9 的数字
问题描述
String str = JOptionPane.showInputDialog("Search for a number from 0-9");
int intNum = Integer.parseInt(str);
try {
File file = new File("numbers.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int num;
int count = 0;
int position = 1;
while ((num = br.read()) != -1) {
if (Character.getNumericValue(num) == intNum) {
System.out.println(intNum + " occurred in " + position + " digit");
count++;
}
position++;
}
JOptionPane.showMessageDialog(null,
intNum + " was found " + count + " times in " + position + " digits", "Result",
JOptionPane.INFORMATION_MESSAGE);
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
numbers.txt 是一个包含数千个数字的文本文件。使用此代码,我只能搜索 0-9 的值,有什么方法可以搜索数字 10、11、12...
澄清:我想在另一个数字中搜索一个数字(例如,在 1 45 6 45 2 中有 2 次出现 45)
解决方案
除了使用 BufferedReader 之外,您还可以使用更奇特的东西来读取整个整数,而不仅仅是单个字符,例如 Scanner。
您可以在此处找到 Scanner.nextInt() 方法:
https://www.programiz.com/java-programming/scanner
(您也可以逐行阅读并自行解析整数。)
推荐阅读
- c - 在 Dev-C++ 中,为什么我导入了项目所需的文件却无法编译我的项目?
- java - Java:从作为参数传递的接口创建匿名类
- php - 如何在 Macbook 上安装 Freetype 扩展
- javascript - 使用 Webpack 的条件需要/导入
- anylogic - 创建具有不同颜色的 ID 的不同类型的托盘,并使用源块插入它们
- intellij-idea - 使用 IntelliJ 时捕获所有日志
- python - 如何在预装的 3.8.2 旁边安装 python 3.6.10
- android - 未找到挂钩“after_prepare”的脚本。在离子科尔多瓦运行android
- css - 如何仅在一个跨度上启用文本选择?
- arrays - System.NullReferenceException 但代码之前有效