Java program that uses a loop to compute the sum of all odd digits of an input. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
Posted by Samath
Last Updated: April 03, 2022
  138

Write a Java program that uses a loop to compute the sum of all odd digits of an input. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)

Code:

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
	    
	    Scanner input = new Scanner(System.in);
	    
	    System.out.print("Please enter number: ");
	    int num = input.nextInt();
	    int k = num;
	    input.close();
	    int result = 0;
	    while (num > 0) {
	        int digit = num % 10;
	        if (digit % 2 != 0) {
		        result += digit;
	   }
	        num /= 10;
	}
	    System.out.printf("Sum of %d odd digits: %d", k, result);
	}
}