Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Part #1: Practice with Recursion Write a recursive method that calculates t

ID: 3725614 • Letter: J

Question

JAVA

Part #1: Practice with Recursion

Write a recursive method that calculates the sum of the digits in an integer. It should have this signature:

Public static int sumDigits(int n)

For example, sumDigits(234) returns 2 + 3 + 4 = 9. Use the main() method to ask the user to enter an integer and then call sumDigits(int).

Part #2: More Practice

Write a recursive method that calculates the number of uppercase letters in a string. The signature should be similar to part one:

Public static int countUpper(String strValue)

For example, countUpper(“Hello World”) returns 2. Use the main() method to ask the user to enter a string and then displays the number of capital letters in the string.

Explanation / Answer

RecursionTester.java

import java.util.Scanner;

public class RecursionTester {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter the number: ");

int n = scan.nextInt();

System.out.println("Sum of digits: "+sumDigits(n)+" " );

System.out.println("Enter the string:");

scan.nextLine();

String s = scan.nextLine();

System.out.println("Count of upper letters: "+countUpper(s));

}

public static int countUpper(String s){

if(s.length()== 0) {

return 0;

} else {

if(Character.isUpperCase(s.charAt(0))){

return 1 + countUpper(s.substring(1));

} else {

return countUpper(s.substring(1));

}

}

}

public static int sumDigits(int n) {

if(n <= 0){

return 0;

}

else {

return (n % 10 ) + sumDigits(n/10);

}

}

}

Output:

Enter the number:
1234
Sum of digits: 10

Enter the string:
Hello World
Count of upper letters: 2