I have to write a recursive method to sum the figures of an integer.
The method works fine, but I don't understand why it returns the last integer instead of the total.
import java.util.Scanner;
public class SommaCifreRicorsivo{
public static void main (String[] args){
System.out.printf("Inserire un numero: ");
Scanner tastiera = new Scanner(System.in);
int numero = tastiera.nextInt();
int somma = 0;
int risultato = eseguiSomma(numero,somma);
System.out.println("La somma delle sue cifre è " + risultato);
}
public static int eseguiSomma(int numero, int somma){
//Caso base
if (numero < 10) {
somma = somma + numero;
System.out.println("Aggiungo la cifra " + numero + " alla somma, ottenendo " + somma);
return (somma += numero);
}
//Chiamate ricorsive
somma = somma + numero%10;
System.out.println("Aggiungo la cifra " + (numero%10) + " alla somma, ottenendo " + somma);
eseguiSomma((numero/10), somma);
return somma;
}
}