java - 查找数字中出现的数字

标签 java

我正在编写一个程序,用户将输入一个数字a并查找a在另一个数字b中出现的次数由用户输入。

    import java.util.Scanner;
    class Number
    {
        public static void main(String args[])
        {
            System.out.println("Enter the digit to match");
            Scanner s=new Scanner(System.in);
            int a=s.nextInt();  //Digit whose occurrence is to find
            System.out.println("Enter the number to match");
            int b=s.nextInt(); //Number in which occurrence is to find
            int ctr=0;
            int ctr1=0;
            while(b!=0) //Number of digits in the entered number
            {
                b/=10;
                ctr++;
            }
            int arr[]=new int[ctr];
            for(int i=0;i<ctr;i++)  //Breaking the number into array of digits
            {
                arr[i]=b%10;
                b/=10;
                if(arr[i]==a)
                {
                    ctr1++;
                }
            }
            System.out.println("Number of occurrences are " +ctr1);
        }
    }

每次输出都是0。我哪里错了?

最佳答案

执行本次循环后

        while(b!=0) //Number of digits in the entered number
        {
            b/=10;
            ctr++;
        }

b 变为 0,因此它只包含 0 以外的任何数字。

您需要将 b 的值存储在某个变量中,并在此循环之后和迭代数字之前重新初始化它。或者,仅使用第一种类型的单个循环 - 您实际上并不在任何地方使用位数。

编辑:另一种方法是将数字转换为字符串,然后使用 lastIndexOf在其上查找给定数字的位置。性能会差一些,但代码会更容易理解(而且更短)。

关于java - 查找数字中出现的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25057271/

相关文章:

java - Java 中以 14400 波特率通过 Comport 进行通信 - 串行通信

java - 嵌入solr有什么问题

java - Jena:如何获取多值属性的值?

java - Jackson 反序列化有界类型

java - json 解析器不适用于 froyo 和 Gingerbread ,但适用于 ics

java - 默认车速?

java - 尤姆和赫罗库

java - Spark中如何只缓存部分RDD?

java - 在 Jackcess 中使用多列索引来匹配第一列

java - 如何在jboss部署中检查classloader类层次结构(优先级)