by BehindJava

WAP to define a method which returns the sum of digits of the given two digit number in Java

Home » interview » WAP to define a method which returns the sum of digits of the given two digit number in Java

In this tutorial we are going to learn about writing a program for the problem statement mentioned below.

Define a method which returns the sum of digits of the given two digit number.
Name of method :getSumOfDigits()
Arguments: one argument of type integer
Return Type: an integer value

Specifications:
If the given value is in between 10 and 99, return sum of it’s digits.
Example: if x = 34, return 7
If the given value is negative, return -3
If the given value is greater than 99, return -2
If the given value is in between 0 and 9, return -1

Sample Code Snippet:

``````public class Sum {
public int getSumOfDigits(int n)
{
int sum=0;
if(n>=10 && n<=99)
{
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
}
else if(n>99)
{
return -2;
}else if(n>=0 && n<=9)
{
return -1;
}else
{
return -3;
}
return sum;
}
public static void main(String[] args) {
//Enables the custom input from the user
Scanner s=new Scanner(System.in);
int n=s.nextInt();

Sum obj=new Sum();
System.out.println(obj.getSumOfDigits(n));
}
}``````