What the title says: I'm writing a program where it calculates and shows the sum of the digits in a number (Ex: 3782 sum = 20).
However, I'm having trouble calling the method I used to calculate it back to the main method - it gives me a "java: cannot find symbol" error.
I need to use a String
for this, and cannot use int
for my values.
Here's my code:
public class digitSum {
//MAIN
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole number: ");
String num = input.nextLine();
//SUM METHOD CALL
// This is the method call I'm having trouble with.
printResult(numSum(sum));
}
//SUM METHOD
static void numSum(int i, String num, int sum) {
for (i = 0; i < num.length(); i++) {
char a = num.charAt(0);
char b = num.charAt(i);
sum = a + b;
}
System.out.println("The digit-sum of" +num+ " is: " +sum);
return;
}
}
You've never defined sum
variable:
int sum = 0;
printResult(numSum(0, num, sum));
Or even better - why passing accumulator and counter to the function if it's not recursive?
static void numSum(String num) {
int sum = 0;
for (int i = 0; i < num.length(); i++) {
char a = num.charAt(0);
char b = num.charAt(i);
sum = a + b;
}
System.out.println("The digit-sum of" +num+ " is: " +sum);
return;
}
Then invoke it by simply calling numSum(num)
.
P.S.: You also need to have printResult
defined (or not - numSum
is printing the result).
@chrylis -on strike- notices, that printing the result of your calculation in the caller would be even better:
static int numSum(String num) {
int sum = 0;
for (int i = 0; i < num.length(); i++) {
char a = num.charAt(0);
char b = num.charAt(i);
sum = a + b;
}
return sum;
}
And in the main
method:
System.out.println(numSum(num));