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); System.out.println();
  9:         printOddDigits(54321); System.out.println();
 10:         printOddDigits(2468); System.out.println();
 11:         printOddDigits(97531); System.out.println();
 12:         printOddDigits(3); System.out.println();
 13:     }

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