81.7k views
1 vote
[Java] Define a method that takes a positive integer number (with maximum two digits) as input and returns the sum of the digits in that number. Then test this new method inside the main method with an input entered by the user (Scanner). Note: Suppose you name your method SumDigits. For example, if you call SumDigits(46) inside the main method, it returns 10 (i.e., 4+6=10).

Hint: Use % operator to extract digits and / operator to remove the extracted digit. For instance, to extract 6 from 46, use 46%10 (=6). Then to remove 6 from 46, use 46/10 (=4).

User Shmuly
by
7.4k points

1 Answer

2 votes

Final answer:

Create a method called SumDigits that takes an integer and returns the sum of its digits. Use the modulus and division operators to manipulate the digits. Test this method in the main method with user input obtained via a Scanner object.

Step-by-step explanation:

To define a method that takes a positive integer number with a maximum of two digits and returns the sum of the digits in that number, we can use both the modulus (%) and division (/) operators to extract and remove digits respectively. The modulus operator is used to obtain the remainder of a division, which in turn can be used to get the last digit of a number by performing number % 10. The division operator is used to remove the last digit by doing number / 10 without needing the remainder.

Here's an example of the method named SumDigits:

public static int SumDigits(int number) {
int sum = 0;
sum += number % 10;
number /= 10;
sum += number;
return sum;
}

And here's how you would test it in the main method using a Scanner to get user input:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a two-digit positive integer: ");
int input = scanner.nextInt();
int result = SumDigits(input);
System.out.println("The sum of the digits is: " + result);
}

User Ahmad Maleki
by
8.0k points

No related questions found