-5
public static void main(String args[]){ 
  System.out.println(countDigitX(8888,8)); 
}

public static intcountDigitX(int n, int x) { 
  return n==0?0:(n%10==x?1:0)+countDigitX(n/10,x); 
}
}//end of class
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • Can you give a bit of details about your issue? – Shmwel May 03 '14 at 07:17
  • 4
    Well do you understand what the conditional operator *does*? If so, it should be fairly easy to rewrite it. If not, see http://stackoverflow.com/questions/798545/what-is-the-java-operator-called-and-what-does-it-do – Jon Skeet May 03 '14 at 07:18
  • yes here is the question : Write a recursive Java method countDigitx that takes two integer numbers as input (a number n and digit x) and returns the number of times digits x occurs in number n: For example if n=23242 and x=2 then the method should return 3 that is the number of times the number 2 found in n. – user3598518 May 03 '14 at 07:21
  • Put the question into the actual question and not buried in the comments please. – ScottMcGready May 03 '14 at 07:24
  • 1
    @ScottMcGready: That's not the actual question, that's just the homework assignment. The question is how to migrate away from ternary syntax. – Makoto May 03 '14 at 07:34

3 Answers3

2
public static intcountDigitX(int n, int x) {
    int result;
    if( n == 0 ) {
        result = 0;
    } else {
        if( n % 10 == x ) {
            result = 1;
        } else {
            result = 0;
        }
        result += countDigitX(n/10, x);
    }
    return result;
}
Peter Chung
  • 457
  • 6
  • 14
0

edit:

         if(n==0) {
         return 0
         }else if(n%10==x){
         return 1+countDigitX(n/10,x);
         }else{
         return 0+countDigitX(n/10,x);
         }
phil652
  • 1,484
  • 1
  • 23
  • 48
0

You can rewrite it as follows :

public static int intcountDigitX(int n, int x) {

        if (n == 0) {
            return 0;
        } else if (n % 10 == x) {
            return 1 + countDigitX(n / 10, x);
        }

        return 0 + countDigitX(n / 10, x);
    }
Visruth
  • 3,430
  • 35
  • 48