首页 > 解决方案 > 读取文件时搜索大于 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)

标签: java

解决方案


除了使用 BufferedReader 之外,您还可以使用更奇特的东西来读取整个整数,而不仅仅是单个字符,例如 Scanner。

您可以在此处找到 Scanner.nextInt() 方法:

https://www.programiz.com/java-programming/scanner

(您也可以逐行阅读并自行解析整数。)


推荐阅读