java—在读取文件时搜索大于9的数字

w41d8nur  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(318)
  1. String str = JOptionPane.showInputDialog("Search for a number from 0-9");
  2. int intNum = Integer.parseInt(str);
  3. try {
  4. File file = new File("numbers.txt");
  5. FileReader fr = new FileReader(file);
  6. BufferedReader br = new BufferedReader(fr);
  7. int num;
  8. int count = 0;
  9. int position = 1;
  10. while ((num = br.read()) != -1) {
  11. if (Character.getNumericValue(num) == intNum) {
  12. System.out.println(intNum + " occurred in " + position + " digit");
  13. count++;
  14. }
  15. position++;
  16. }
  17. JOptionPane.showMessageDialog(null,
  18. intNum + " was found " + count + " times in " + position + " digits", "Result",
  19. JOptionPane.INFORMATION_MESSAGE);
  20. br.close();
  21. fr.close();
  22. } catch (FileNotFoundException e) {
  23. System.out.println("An error occurred.");
  24. e.printStackTrace();
  25. }
  26. }

numbers.txt是一个包含数千个以上数字的文本文件。用这个代码我只能搜索0-9之间的值,有没有什么方法可以搜索数字10,11,12。。。
澄清:我想在另一个号码中搜索一个号码(例如,1456452中出现了2个45)

fdbelqdn

fdbelqdn1#

找到大于9的数字
使用bufferedreader非常好:

  1. try (BufferedReader br = new BufferedReader(new FileReader("your/file/path"))) {
  2. String s;
  3. while ((s = br.readLine()) != null) {
  4. String[] s1 = s.split(" ");
  5. for (int i = 0; i < s1.length; i++) {
  6. if (s1[i].matches("\\d+")) {
  7. int num = Integer.parseInt(s1[i]);
  8. if (num > 9) {
  9. System.out.println("Found number bigger than 9 (" + num + ")");
  10. }
  11. }
  12. }
  13. }
  14. } catch (Exception e) {
  15. //log
  16. }
  17. ``` `br.readLine()` 读下一行。将行按空格分开,然后检查行中的每个单词是否有数字。如果单词是数字(用正则表达式验证 `\\d+` ),然后检查是否大于9。
  18. 再说一遍 `Scanner` 使工作更容易:

Scanner scanner;
try {
scanner = new Scanner(new File("your/file/path"));
while(scanner.hasNextLine()) {
while(scanner.hasNextInt()) {
int cur = scanner.nextInt();
if(cur > 9) {
System.out.println("Found number bigger than 9 ("+cur+")");
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

  1. 在另一个号码中搜索号码

try(BufferedReader br = new BufferedReader(new FileReader("your/file/path"))){
String s;
Scanner sc = new Scanner(System.in);
int lookFor = Integer.parseInt(sc.nextLine());
String read = br.readLine();
int len = String.valueOf(lookFor).length();
int found = 0;
for(int i = 0; i+len < read.length(); i++) {
String cur = read.substring(i, i+len);
if(Integer.parseInt(cur)==lookFor) {
found++;
}
}
}
System.out.println("Found: "+found);

  1. 尽管您提到文本文件包含数十亿个数字,但我想指出 `String` 能容纳的是 `Integer.MAX_VALUE` . 如果你得到一个 `OutOfMemoryException` 因为数字太多了。
展开查看全部
wbgh16ku

wbgh16ku2#

您可以使用一些更奇特的东西来读取整个整数,而不仅仅是单个字符,例如scanner,而不是只使用bufferedreader。
这里有一个scanner.nextint()方法:
https://www.programiz.com/java-programming/scanner
(您也可以逐行读取并自行解析整数。)

相关问题