JackedJacked123 - 8 months ago 39

Java Question

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?

Answer

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

Source (Stackoverflow)