Method to filter Java figures

1

I'm trying to create a Java method that filters figures as follows: The method asks for two int (int n, int x). If n is, for example, 4232 and x is 2, n will be filtered making all 2 of n change to zeros, that is; filterCifrasX (4232, 2) returns the integer 4030. I've tried a few things but I can not. Thanks in advance for the help.

public static int filtraCifrasX(int n, int x) {
     if (n < 10) {if (n==x) {return 0;} else {return n;}}
    else {
        if (n%10 == x) {n = n-n%10;filtraCifrasX(n/10,x);return n;}
        else {return filtraCifrasX(n/10,x);}
    }
}

This is the method as I have it right now, the problem I have is that if I enter 4232 as I had set an example, it returns 4230; but not 4030, which is what should happen.

    
asked by eddthulhu 08.03.2018 в 00:22
source

2 answers

1

First you convert the number of "n" to a String

int n = 4232
String cifra = String.valueOf(n)

then replace the numbers "2" with "0" as follows

cifra.replaceAll("2","0");

and ready at the end you have to set that number again as an integer

n = Integer.parseInt(n);
    
answered by 08.03.2018 в 00:30
0

I have already managed to get the method to work exactly as I wanted, I leave it here in case someone needs it at some time.

/** Devuelve un entero con las mismas cifras que n, excepto que las
 * apariciones del digito x aparecen cambiadas por 0.
 * Precondicion: n >= 0, 1 <= x <= 9.
 */
public static int filtraCifrasX(int n, int x) {
    if (n < 10) {if (n==x) {return 0;} else {return n;}}
    else {
        if (n%10 == x) {return filtraCifrasX(n/10,x)*10;}
        else {return filtraCifrasX(n/10,x)*10 + n%10;}
    }
}
    
answered by 08.03.2018 в 01:55