Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Scanner;
- public class LoopsEx02Slide61 {
- public static void main(String[] args) {
- // input: two integer number. example: n1=37, n2=81
- // output: merged number from n1 and n2. example: 3871
- // example: n1=12, n2=3456, output is: 341526
- // create a scanner
- Scanner s = new Scanner(System.in);
- // ask for input
- System.out.print("Enter the first number: ");
- // get and save input value
- int n1 = s.nextInt();
- // ask for input
- System.out.print("Enter the seconed number: ");
- // get and save input value
- int n2 = s.nextInt();
- // close scanner
- s.close();
- int tmp1 = n1, tmp2 = n2; // calculated: number with digits to be merged
- int newNumber = 0;// output: the new number with even digits only
- int weight = 1; // the value of the even digit to be add to newNumber
- // while there are more digits to check
- while (tmp1 > 0 && tmp2 > 0) {
- // add first digit from tmp2 to newNumber
- newNumber += (tmp2 % 10) * weight;
- // update the value of the digit
- weight *= 10;
- // add first digit from tmp1 to newNumber
- newNumber += (tmp1 % 10) * weight;
- // update the value of the digit
- weight *= 10;
- // drop used (merged) digits from tmp1 and tmp2
- tmp1 /= 10; // drop merged digit from tmp1
- tmp2 /= 10; // drop merged digit from tmp2
- }
- // in case n1 and n2 do not have the same number of digits
- int more = tmp1 > 0 ? tmp1 : tmp2; // the extra digits to be copied to
- // the new number
- // add extra digits to newNumber
- newNumber += (more) * weight;
- // display output on the screen
- System.out.printf("n1 =%d, n2=%d\nmerged=%d\n", n1, n2, newNumber);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement