# Sum digits of two integers

#1

How can I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!

``````public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);``````

#2

You posted in the wrong Thread by the way. This should be in the Java section but anyways you can try this.

``````import java.util.*;

public class  Test  {

public static  int sumNumber(int num){
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
return sum;
}
public static void main(String[] args) {
//create a scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter two numbers separated by a whitespace");

//define input format with regex
String regex = "\\d+\\s+\\d+";

// prompt for input
String input = in.nextLine();

int total = 0;
//if user's input does not match pattern designed prompt again
while(!(input.matches(regex))){
System.out.println("Invalid input");
System.out.println("Enter two numbers separated by a whitespace");
input = in.nextLine();
}
//split the input
String[] tokens = input.split("\\s+");
for(String s:tokens){
total+=sumNumber(Integer.parseInt(s));
}

System.out.println("The sum of the digits of the two numbers is "+total);

}

}``````

You can just write the method to sum up the integers in a number an Then write a program in the main where the user enters a bunch of numbers and then you evaluate the digits.

# Sample run results

``````Enter two numbers separated by a whitespace
56
Invalid input
Enter two numbers separated by a whitespace
rtrtrtrew dsdsdsds
Invalid input
Enter two numbers separated by a whitespace
Invalid input
Enter two numbers separated by a whitespace
45/56
Invalid input
Enter two numbers separated by a whitespace
45                  67
The sum of the digits of the two numbers is  22``````

#3

Are you okay with this?

#4

Yup. I kept working on the problem while I waited for a response, so when I saw your answer, I was a little further along than I was when I posted the question. Your answer really helped me finally finish solving the problem though. Thanks!