【问题标题】:Recursion: Frequency of digit in a scanned number: redux递归:扫描数字中数字的频率:redux
【发布时间】:2020-03-08 16:48:57
【问题描述】:

我今天早些时候问了一个类似的问题,关于在通过文本扫描的数字中查找一种数字(硬编码)。我考虑了是否输入了用户正在寻找的数字并开始研究。我可以找到很多“查找所有数字的频率”,但没有找到关于用户输入的内容。我了解将 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 个整数)。无法弄清楚将整数和方法输入到一个变量中的调用。

【问题讨论】:

  • 尝试正确格式化您的代码。您的示例似乎遗漏了一些}。您还必须将 digitArray 作为参数传递给递归函数(除非它是类的字段)。
  • 谢谢,我已经正常关闭了。我没有完成 digitArray。这就是我陷入困境的地方,即如何调用和比较。
  • 你有什么问题?
  • 我的问题是,我怎样才能准确地获得我的方法来比较输入的数字并与扫描的数字进行比较并计算该数字出现的实例数。
  • 如果你的 count 方法应该递归工作,你不想在其中有一个循环。相反,您需要决定是进行另一次递归还是返回结果。此外,如果您打算计算不同的数字,则您的回报不能是单个 int

标签: java arrays recursion java.util.scanner


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多