Writing in Java, write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: ouput the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, output the individual digits of 4000 as 4 0 0 0 and the sum as 4, and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.

Respuesta :

Answer:

//Here is code in java.

import java.util.*;

class Main

{

public static void main (String[] args) throws java.lang.Exception

{

   try{

       int in;

     //scanner class object to read the input

    Scanner scr=new Scanner(System.in);

     // variable to keep running total

    int total=0;

    System.out.println("please enter an Integer:");

     // read the input first time

    in=scr.nextInt();

    System.out.print("individual digits of "+in+" is ");

    if(in<0)

    {

        in=-(in);

    }

   

 

     //call the function to print the digits of number

   print_dig(in);

   System.out.println();

    //calculate the sum of all digits

   do{

       int r=in%10;

       total=total+r;

       in=in/10;

   }while(in>0);

    //print the sum

   System.out.println("total of digits is: "+total);

     

   }catch(Exception ex){

       return;}

}

 //recursive function to print the digits of number

public static void print_dig(int num)

{  

    if(num==0)

    return;

    else

    {

    print_dig(num/10);

    System.out.print(num%10+" ");

    }

}

}

Explanation:

Read a number with the help of object of scanner class.if the input is negative

then make it positive number before calling the function print_dig().call

the recursive method print_dig() with parameter "num".It will extract the digits

of the number and print then in the order. Then in the main method, calculate

sum of all the digits of number.

Output:

please enter an Integer:                                                                                                  

3456                                                                                                                      

individual digits of 3456 is 3 4 5 6                                                                                      

total of digits is: 18

please enter an Integer:                                                                                                  

-2345                                                                                                                      

individual digits of -2345 is 2 3 4 5                                                                                      

total of digits is: 14

ACCESS MORE
EDU ACCESS