我正在编写一个程序,用户将在其中输入数字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.我错了?
答案 0 :(得分:3)
执行此循环后
while(b!=0) //Number of digits in the entered number
{
b/=10;
ctr++;
}
b变为0,因此它不包含数字而是0。
您需要将b的值存储在某个变量中,并在此循环之后和迭代数字之前重新初始化它。或者只使用第一种类型的单个循环 - 您实际上并未使用任何位数。
编辑:另一种方法是将数字转换为字符串,然后在其上使用lastIndexOf来查找找到给定数字的位置。性能会稍差,但代码会更容易理解(和更短)。
答案 1 :(得分:1)
以下内容:
int count=0;
char a = (char)(47 + s.nextInt());
char[] b = s.nextInt().ToString().ToCharArray();
for(int i=0; i < b.lenght(); i++)
{
if(b[i]==a)
{
count++;
}
}
答案 2 :(得分:0)
我可以找到的一个基本错误是您修改了b来获取数字位数,因此您无法从中获取单个位。
在修改b。
的值之前,尝试将其复制到单独的变量中答案 3 :(得分:-1)
执行此操作时,b始终为0.
arr[i]=b%10;