Recursion: Frequency of digit in a scanned number: redux

294 views Asked by At

I asked a similar question earlier today in regards to finding a type of digit (hard coded) in a number that was scanned in through text. I thought about if there was an input of what digit the user is looking for and started to research. I can find plenty of "find frequency of all digits" but none about user input. I understand converting int to string and counting characters, but I wanted to find another way of doing it, hopefully using recursion.

My main is set (I believe):

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

edited to show progress

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

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

**I simplified the return to show the count, but now I have "actual and formal argument lists differ in length" error (2 ints in method, 1 in main). Can't figure out the call to input both integers and method into one variable.

1

There are 1 answers

0
fedup On

I don't think you need to convert the input from the file into a number at all. You can scan the String for the char you need. Also I have shown it as a recursive function.

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