76.3k views
5 votes
Write a program which asks the user to enter an integer. Your program should then display the sum of the even digits of the integer. A typical run would be: Enter an integer greater than 10000: 34 34 is not greater than 10000 Enter an integer greater than 10000: 39428 The sum of the even digits of 39248 is: 14 Hints: Use a loop to ensure that the number entered is > 10000. You don’t need to be concerned with the length of the integer, use a while loop which ends when the number is equal to zero. You will need to preserve the original value entered, so after the user enters it, copy it to another int variable. You can access the last digit of an integer by dividing modulo by 10, eg digit = workingNumber % 10; You can remove the last digit of an integer by dividing by 10, eg workingNumber /= 10;

1 Answer

4 votes

Answer:

The program in Java is as follows:

import java.util.*;

public class Main{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int sumeven = 0;

System.out.print("Enter an integer greater than 10000: ");

int number = input.nextInt();

while(number <= 10000){

System.out.print(number+" is not greater than 10000\\Enter an integer greater than 10000: ");

number = input.nextInt(); }

System.out.print("The sum of the even digits of "+number+" is ");

while (number > 0) {

if ((number%10)%2== 0){

sumeven+=(number%10); }

number = number / 10; }

System.out.print(sumeven);

}

}

Step-by-step explanation:

This initializes the sum of even digirs to 0

int sumeven = 0;

This prints the prompt for input

System.out.print("Enter an integer greater than 10000: ");

This gets the input from the user

int number = input.nextInt();

This loop is repeated until the input is greater than 10000

while(number <= 10000){

System.out.print(number+" is not greater than 10000\\Enter an integer greater than 10000: ");

number = input.nextInt(); }

This prints the output header

System.out.print("The sum of the even digits of "+number+" is ");

This loop is repeated until there is no digit left in the user input

while (number > 0) {

This checks if individual digit is even

if ((number%10)%2== 0){

If yes, then the sum is taken

sumeven+=(number%10); }

This gets the next digit

number = number / 10; }

This prints the calculated sum

System.out.print(sumeven);

User AliNajafZadeh
by
5.7k points