Source of PrintOddDigits.java


  1: //PrintOddDigits.java
  2: //Prints the odd digits of an integer in the original order.

  4: public class PrintOddDigits
  5: {
  6:     public static void main(String[] args)
  7:     {
  8:         printOddDigits(123);
  9:         System.out.println();
 10:         printOddDigits(54321);
 11:         System.out.println();
 12:         printOddDigits(2468);
 13:         System.out.println();
 14:         printOddDigits(97531);
 15:         System.out.println();
 16:         printOddDigits(3);
 17:         System.out.println();
 18:     }

 20:     /**
 21:         Print the odd digits of an integer in the same order as they
 22:         appear in the integer.
 23:         @param n The integer whose odd digits are to be printed.
 24:         <p>Pre:<p>n has been initialized with a positive integer.
 25:         <p>Post:<p>Only the odd digits of n have been displayed,
 26:         in the same order in which they appeared in n.
 27:     */
 28:     public static void printOddDigits(int n)
 29:     {
 30:         if (n < 10)
 31:         {
 32:             if (n % 2 == 1)
 33:                 System.out.print(n);
 34:         }
 35:         else
 36:         {
 37:             int temp;
 38:             temp = n % 10;
 39:             printOddDigits(n / 10);
 40:             if (temp % 2 == 1) System.out.print(temp);
 41:         }
 42:     }
 43: }