java - 递归:扫描数字中数字的频率:redux

标签 java arrays recursion java.util.scanner

今天早些时候,我问了一个类似的问题,涉及在通过文本扫描的数字中查找某种类型的数字(硬编码)。我考虑是否输入了用户正在寻找的数字并开始研究。我可以找到很多“查找所有数字的频率”,但没有关于用户输入的内容。我了解将 int 转换为字符串并计算字符数,但我想找到另一种方法,希望使用递归。

我的主要内容已设置(我相信):

Scanner scanner = new Scanner(new File("countdigits.txt"));
    int Number = 0;
    int[] digit = new int [10];
    digit[] = {0,1,2,3,4,5,6,7,8,9};
    int remainder = 0;
    while(scanner.hasNextInt())
    {
        Number = scanner.nextInt();
    }

    System.out.println("Okay, which number (0-9) would you like to find?");
    digit = input.nextInt();
    try {
        if (digit < 0 || digit > 9) throw new IOException();

} catch (IOException f) {
    System.out.println("Funny.  Exiting");
    int Count = count(Number);

    System.out.format("** Number of digits in given number = %d", Count);
}

已编辑以显示进度

private static int count(int number, int digit) {

return (number % 10 == digit ? 1 :0) + count(number / 10);
}

**我简化了返回以显示计数,但现在出现“实际参数列表和形式参数列表长度不同”错误(方法中 2 个整数,主函数中 1 个)。无法弄清楚将整数和方法输入到一个变量中的调用。

最佳答案

我认为您根本不需要将文件的输入转换为数字。您可以扫描字符串以查找所需的字符。我也将其显示为递归函数。

public static void main(String... args) {

    Scanner input = new Scanner(System.in);
    try {
        Scanner scanner = new Scanner(new File("countdigits.txt"));
        while (scanner.hasNext()) {
            String word = scanner.next();

            System.out.println("Okay, which number (0-9) would you like to find?");
            String digitInput = input.next();
            if (digitInput.length() != 1) {
                throw new IOException("only a single digit is allowed");
            }
            char targetDigit = digitInput.charAt(0);
            if (targetDigit < '0' || targetDigit > '9') {
                throw new IOException("only numbers are allowed");
            }

            int count = count(word, targetDigit, 0);
            System.out.format("** Number of digits in given number = %d", count);
        }

    } catch (IOException f) {
        System.out.println("Funny.  Exiting");
    }
}

private static int count(String word, char targetDigit, int targetStart) {
    int targetLoc = word.indexOf(targetDigit, targetStart);
    if (targetLoc < 0) {
        return 0;
    }
    return 1 + count(word, targetDigit, targetLoc + 1);
}

关于java - 递归:扫描数字中数字的频率:redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58827790/

相关文章:

java - 如何清理输入

arrays - 如何从 C 指针创建 Racket 可变数组来修改 OpenCV 图像?

java - 将所有文件递归保存在列表中

c++ - 具有无限子节点的树的递归函数。 C++

c# - 奇怪的单声道编译错误

java - Android:从 JSON 动态获取 JSON 数组键名

arrays - 如果条件匹配, typescript 数组删除项目

C 在完成关闭函数时崩溃

MySQL不支持递归函数?为什么?从何时起?

java - 在 pom.xml 中配置 Maven 插件两次