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.
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.