-2

Write a Java function count digits(int num); where num is a positive integer. The function counts how many times each of the digits 0..9 appears in num, and prints the results (see the following example below). Example: Calling count digits(347213); will print the following: "The number 0 appaeared 0 times in 347213.... (same with 1, 2, 3).. No helper/recursion allowed, only iteration.

import java.Math.;

public int count-digits (int num){
int count = 0;
String numF = string.valueOf(num);
  // We get the number of digits by logs.
  for(int j=0; j <= 9; j++){ //loop for each digits
    for(int i=0; i < Math.floor(Math.log10(num)); i++){ //this loops checks each no.
      if(numF.charAt(j).equals(i)){
         count++;
      }
      return count;
      count=0;
    }      
  }
}

Two problems:

(1) How do I return the string alongside to it?

(2) Does this work? Is there a better solution?

Dani M
  • 1,173
  • 1
  • 15
  • 43

1 Answers1

0
public void countDigits(int num) {      
    int count=0;
    String numF = String.valueOf(num);

    for (int j = 0; j <= 9; j++) {
        count=0;
        for (i = 0; i <numF.length(); i++) {
            char c = numF.charAt(i);
            String number=String.valueOf(j);
            if (c == number.charAt(0)) {
                count++;
            }
        }
        System.out.println("The number " + j + " appaeared " + count + " times in 347213");

    }
}

for this method you get an output like this

The number 0 appaeared 0 times in 347213
The number 1 appaeared 1 times in 347213
The number 2 appaeared 1 times in 347213
The number 3 appaeared 2 times in 347213
The number 4 appaeared 1 times in 347213
The number 5 appaeared 0 times in 347213
The number 6 appaeared 0 times in 347213
The number 7 appaeared 1 times in 347213
The number 8 appaeared 0 times in 347213
The number 9 appaeared 0 times in 347213

You cant compare chars with equals. Therefor you have need to have 2 chars you can compare with == and since you cant convert int to char u get a string with length of 1 and take first char. I hope this i what you are looking for.

XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
  • 1
    Instead of `for (int j = 0; j <= 9; j++)` I'd go with `for (char j = '0'; j <= '9'; j++)`. No need to do `String number = String.valueOf(j)` then, as you can just do `if (c == j)` – daiscog Nov 11 '16 at 13:19
  • well yeah seems to work just fine. Didn't know it was possible to iterate with char. thanks for the tip – XtremeBaumer Nov 11 '16 at 13:22
  • Yep. `char` is a primitive type (just a 16-bit signed integer), so you can do all the same mathematical operations on it. Just need to remember that `'0' != 0` (note the quote marks). – daiscog Nov 11 '16 at 13:23