Advertisement
mmayoub

Loops - execise no 02, slide no 61

Jun 27th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class LoopsEx02Slide61 {
  6.  
  7.     public static void main(String[] args) {
  8.         // input: two integer number. example: n1=37, n2=81
  9.         // output: merged number from n1 and n2. example: 3871
  10.         // example: n1=12, n2=3456, output is: 341526
  11.  
  12.         // create a scanner
  13.         Scanner s = new Scanner(System.in);
  14.  
  15.         // ask for input
  16.         System.out.print("Enter the first number: ");
  17.         // get and save input value
  18.         int n1 = s.nextInt();
  19.         // ask for input
  20.         System.out.print("Enter the seconed number: ");
  21.         // get and save input value
  22.         int n2 = s.nextInt();
  23.         // close scanner
  24.         s.close();
  25.  
  26.         int tmp1 = n1, tmp2 = n2; // calculated: number with digits to be merged
  27.         int newNumber = 0;// output: the new number with even digits only
  28.         int weight = 1; // the value of the even digit to be add to newNumber
  29.  
  30.         // while there are more digits to check
  31.         while (tmp1 > 0 && tmp2 > 0) {
  32.             // add first digit from tmp2 to newNumber
  33.             newNumber += (tmp2 % 10) * weight;
  34.             // update the value of the digit
  35.             weight *= 10;
  36.  
  37.             // add first digit from tmp1 to newNumber
  38.             newNumber += (tmp1 % 10) * weight;
  39.             // update the value of the digit
  40.             weight *= 10;
  41.  
  42.             // drop used (merged) digits from tmp1 and tmp2
  43.             tmp1 /= 10; // drop merged digit from tmp1
  44.             tmp2 /= 10; // drop merged digit from tmp2
  45.         }
  46.  
  47.         // in case n1 and n2 do not have the same number of digits
  48.         int more = tmp1 > 0 ? tmp1 : tmp2; // the extra digits to be copied to
  49.                                             // the new number
  50.         // add extra digits to newNumber
  51.         newNumber += (more) * weight;
  52.  
  53.         // display output on the screen
  54.         System.out.printf("n1 =%d, n2=%d\nmerged=%d\n", n1, n2, newNumber);
  55.  
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement