整数[Java]中的数字出现了多少次

整数[Java]中的数字出现了多少次,java,algorithm,Java,Algorithm,编写一个Java函数计数位数(int num);其中num是一个正整数。该函数统计数字0..9在num中出现的次数,并打印结果(参见下面的示例)。 示例:呼叫计数数字(347213);将打印以下内容:“数字0在347213中经过0次处理……(与1、2、3相同)不允许使用帮助器/递归,只允许迭代 导入java.Math。; 公共整数计数位数(整数){ 整数计数=0; String numF=String.valueOf(num); //我们通过日志获得位数。 对于(int j=0;j 您不能将字符

编写一个Java函数计数位数(int num);其中num是一个正整数。该函数统计数字0..9在num中出现的次数,并打印结果(参见下面的示例)。 示例:呼叫计数数字(347213);将打印以下内容:“数字0在347213中经过0次处理……(与1、2、3相同)不允许使用帮助器/递归,只允许迭代

导入java.Math。;
公共整数计数位数(整数){
整数计数=0;
String numF=String.valueOf(num);
//我们通过日志获得位数。
对于(int j=0;j
您不能将字符与
等于
进行比较。因此,您需要有两个字符,您可以与
=
进行比较,并且由于您无法将
int
转换为
char
u,因此您需要一个长度为1的字符串,并获取第一个字符。
我希望这就是你要找的。

这段代码甚至没有编译将int转换为字符串,然后使用以下方法:它说“不允许使用帮助程序”,所以我不会发布答案。返回类型是int,你在它旁边的字符串是什么意思,你的计数=0是不可访问的!你甚至尝试过这个方法吗!而不是
(int j=0;j是的,似乎工作得很好。我不知道可以使用char进行迭代。感谢您的提示。
char
是一种基本类型(仅为16位有符号整数),因此您可以对其执行所有相同的数学运算。只需记住
'0'!=0
(注意引号)。
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;
    }      
  }
}
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");

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