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

w41d8nur  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(310)
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。。。
澄清:我想在另一个号码中搜索一个号码(例如,1456452中出现了2个45)

fdbelqdn

fdbelqdn1#

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

try (BufferedReader br = new BufferedReader(new FileReader("your/file/path"))) {
  String s;
  while ((s = br.readLine()) != null) {
    String[] s1 = s.split(" ");
    for (int i = 0; i < s1.length; i++) {
      if (s1[i].matches("\\d+")) {
        int num = Integer.parseInt(s1[i]);
        if (num > 9) {
          System.out.println("Found number bigger than 9 (" + num + ")");
        }
      }
    }
  }
} catch (Exception e) {
  //log
}
``` `br.readLine()` 读下一行。将行按空格分开,然后检查行中的每个单词是否有数字。如果单词是数字(用正则表达式验证 `\\d+` ),然后检查是否大于9。
再说一遍 `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();
}

在另一个号码中搜索号码

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);

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

wbgh16ku2#

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

相关问题