Impact Pixel
Impact Pixel

Reputation: 5

I need to separate a integer then add the digits together in java

Good morning, I am on now to lesson 4 and am having a bit of trouble using loops. Please note that I have seen it resolved using strings but I am trying to grasp loops.

The reason for the trouble is I need to show both answers: The integer broken into individual number ex: 567 = 5 6 7

And then 567 = 18

I am able to get the integer added together but am not sure on how to separate the integer first and then add the individual numbers together. I am thinking that I need to divide down to get to 0. For instance if its a 5 digit number /10000, /1000, /100, /10, /1

But what if the user wants to do a 6 or 7 or even a 8 digit number?

Also I am assuming this would have to be first and then the addition of the individual integers would take place?

thanks for the guidance:

import java.util.Scanner;

public class spacing {

      public static void main(String[] args) {

            Scanner in = new Scanner(System.in);

            int n;

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

            n = in.nextInt();   

                  int sum = 0;          

                  while (n != 0) {

                        sum += n % 10;

                        n /= 10;

                  }
                  System.out.println("Sum: " + sum);

        }
}

Upvotes: 0

Views: 11914

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76434

//I assume that the input is a string which contains only digits
public static int parseString(String input)
{
    char[] charArray = input.toCharArray();
    int sum = 0;
    for (int index = 0; index < input.length; index++)
    {
        sum += Integer.parseInt(charArray[index] + "");
    }
    return sum;
}

Use the function above, pass your input to the function and use the output as you like.

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95508

Since this is a lesson, I won't give you the solution outright, but I will give you some hints:

  1. You're only thinking in int. Think in String instead. :) This will also take care of the case where users provide you numbers with a large number of digits.
  2. You will need to validate your input though; what if someone enters "12abc3"?
  3. String.charAt(int) will be helpful.
  4. Integer.parseInt(String) will also be helpful.

You could also look at using long instead of int; long has an upper limit of 9,223,372,036,854,775,807 though.

Upvotes: 5

Related Questions