我想知道在另一个号码中出现1个号码的次数。我找到了另一个号码中找到2位数字的解决方案,但我想要做的是找到提供的数字中的1位,2位,......,n位数字。我不想在开关指令中创建另一个案例,所以我的问题是如何避免切换以使其工作。代码如下:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Provide number:");
int number1 = sc.nextInt();
System.out.println("Provide number you want to find in number1:");
int number2 = sc.nextInt();
int counter = 0;
int digit = 1;
int a = 10;
while(number2/a>0){
digit++;
a = a*10;
}
switch(digit){
case 1:{
while(number1 > 0 ){
if(number1 % 10 == number2){
counter++;
}
number1 = number1/10;
}
}
case 2:{
while(number1 > 0){
if(number1 % 100 == number2){
counter++;
}
number1 = number1/10;
}
}
}
System.out.println(counter);
}
感谢您的帮助。
答案 0 :(得分:0)
嗯,你已经得到了答案。只需使用你的变量a。
while(number1 > 0){
if(number1 % a == number2){
counter++;
}
number1 = number1/10;
}
答案 1 :(得分:0)
正如家里的工作,只是一些想法。
int entireNumber = 12345;
int soughtPartNumber = 234;
// Find the power of 10 that caps the soughtPartNumber (1000):
int cap = 1;
while (soughtPartNumber * 10 < cap) {
cap *= 10;
}
// Search in the number as you did:
while (entireNumber >= soughtPartNumber) {
... (entireNumber % cap) == ...
entireNumer /= 10; // Remove the right digit
}