Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Scanner;
- public class LoopsEx01Slide58 {
- public static void main(String[] args) {
- // input: integer number. example: 123467
- // output: number with the even digits only. example: 246
- // create a scanner
- Scanner s = new Scanner(System.in);
- // ask for input
- System.out.print("Enter an integer number: ");
- // get and save input value
- int n = s.nextInt();
- // close scanner
- s.close();
- int tmp = n; // calculated: number with digits to be checked
- 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 (tmp > 0) {
- // calculate most right digit
- int digit = tmp % 10; // calculated: current digit to be checked
- // if even digit then
- if (digit % 2 == 0) {
- // copy it to the new number
- newNumber += digit * weight;
- // update the value of the digit
- weight *= 10;
- }
- tmp /= 10; // drop this digit and continue to check the others
- }
- // display output on the screen
- System.out.printf("input =%d\noutput=%d\n", n, newNumber);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement