Java 替换该代码中的开关指令

Java 替换该代码中的开关指令,java,Java,我想知道一个数字在另一个数字中出现了多少次。我已经找到了在另一个数字中查找2位数字的解决方案,但我想做的是在提供的数字中查找1位、2位、…、n位数字。我不想在switch指令中创建另一个案例,所以我的问题是如何避免使用switch使其工作。代码如下: public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Provide number:")

我想知道一个数字在另一个数字中出现了多少次。我已经找到了在另一个数字中查找2位数字的解决方案,但我想做的是在提供的数字中查找1位、2位、…、n位数字。我不想在switch指令中创建另一个案例,所以我的问题是如何避免使用switch使其工作。代码如下:

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

谢谢你的帮助。

你已经得到了答案。只需使用变量a

while(number1 > 0){
   if(number1 % a == number2){
        counter++;
   }
   number1 = number1/10;
}

这散发着家庭作业的味道,只是一些想法

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
}
int entireNumber=12345;
int soughtPartNumber=234;
//查找限制soughtPartNumber(1000)的10的幂:
int cap=1;
同时(soughtPartNumber*10=soughtPartNumber){
…(完整编号%cap)=。。。
entireNumer/=10;//删除右边的数字
}

我应该将此指令添加到case还是添加它而不是case?请删除case指令并用此指令替换它。应该很好用。你可以用Eggen先生的表达式(number1>=number2)来更改我的说明中的表达式,当number2的位数大于1时效果会好得多。我不懂while循环二次。更具体地说,“…(entireNumber%cap)==…”在做什么?我并没有写全部。一个人会做12345%1000==345;1234 % 1000 == 234, 123