Skip to Main Content

Merging two codes into one

20845a37-069e-4d44-9271-10facb6cd0e9Jun 7 2015 — edited Jun 8 2015

I have a homework assignment: 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. 

Now I have a code for spacing out the integers, and I have a separate code for adding the digits. But I am not sure how to merge them together. Both of them work independently but I am very much a newbie at this, any help would be appreciated.

Spacing code:

import java.util.*;

public class SumoftheIntegers

{

static Scanner console=new Scanner(System.in);

public static void main(String []args)

{

int num1, test, rem;

int counter = 0;

System.out.print("Enter a number: ");

num1=console.nextInt();

test = num1;

while (test > 0)

{

  test  = test/10;

  counter = counter + 1;

}

counter = counter - 1;

while (counter >= 0)

{

   rem = num1% (int) Math.pow(10, counter);

   num1 = num1/(int) Math.pow(10,counter);

   System.out.print (num1 + " ");

   num1 = rem;

   counter = counter - 1;

}

}

}

Now the sum of the integers code:

import java.util.Scanner;

public class sum

{

    public static void main(String[] args)

    {

        // Create a Scanner

        Scanner input = new Scanner(System.in);

        // Enter amount

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

        int integer = input.nextInt();

        // Calculations

        int rinteger = Math. abs (integer);

        int sum = 0;

        int i=0;

        //loop through each digit (starting from the least significant) until the end of the number

        while(rinteger / Math.pow(10,i) > 0)

        {

            sum+=getDigit(rinteger,i);

            i++;

        }

        // Display results

        System.out.println("Sum all digits in " + integer + " is " + sum);

    }

    public static int getDigit(int num, int power)

    {

        return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);

    }

}

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked due to inactivity on Jul 6 2015
Added on Jun 7 2015
3 comments
214 views