Advertisement
mmayoub

Loops - execise no 01, slide no 58

Jun 27th, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class LoopsEx01Slide58 {
  6.  
  7.     public static void main(String[] args) {
  8.         // input: integer number. example: 123467
  9.         // output: number with the even digits only. example: 246
  10.  
  11.         // create a scanner
  12.         Scanner s = new Scanner(System.in);
  13.  
  14.         // ask for input
  15.         System.out.print("Enter an integer number: ");
  16.         // get and save input value
  17.         int n = s.nextInt();
  18.  
  19.         // close scanner
  20.         s.close();
  21.  
  22.         int tmp = n; // calculated: number with digits to be checked
  23.         int newNumber = 0;// output: the new number with even digits only
  24.         int weight = 1; // the value of the even digit to be add to newNumber
  25.  
  26.         // while there are more digits to check
  27.         while (tmp > 0) {
  28.             // calculate most right digit
  29.             int digit = tmp % 10; // calculated: current digit to be checked
  30.  
  31.             // if even digit then
  32.             if (digit % 2 == 0) {
  33.                 // copy it to the new number
  34.                 newNumber += digit * weight;
  35.  
  36.                 // update the value of the digit
  37.                 weight *= 10;
  38.             }
  39.             tmp /= 10; // drop this digit and continue to check the others
  40.         }
  41.  
  42.         // display output on the screen
  43.         System.out.printf("input =%d\noutput=%d\n", n, newNumber);
  44.  
  45.     }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement