I am trying to do the following program in Java
where I'm writing a recursive and an iterative method to compute the sum of all odd numbers from n
to m
import java.util.Scanner;
public class AssignmentQ7 {
public static int recursivesum(int n, int m){ if (n < m){ int s = n; s += recursivesum(n+2, m); } else{ if(m < n){ int s = m; s += recursivesum(m+2, n); } } return s; } public static int iterativesum(int n, int m){ if(n < m){ int s = n; for(int i = n; i <= m; i += 2){ s += i; return s; } } else if(m < n){ int s = m; for(int i = m; i <= n; i += 2){ s += i; return s; } } } public static void main(String args[]){ int n,m; Scanner in = new Scanner(System.in); System.out.println("Enter two numbers: "); n = in.nextInt(); m = in.nextInt(); while(n%2 == 0){ System.out.println("Enter the first number again: "); n = in.nextInt(); } while(m%2 == 0){ System.out.println("Enter the second number again: "); m = in.nextInt(); } System.out.println("The answer of the recursive sum is: " + recursivesum(n,m)); System.out.println("The answer of the iterative sum is: " + iterativesum(n,m)); } }
I'm getting an error cannot find symbol - variable enter code here
s. I don't know what's wrong! Can anyone help please?
This method is the problem:
public static int recursivesum(int n, int m) {
if (n < m) {
int s = n; // Variable declared here... scoped to the if
s += recursivesum(n+2, m);
} else {
if (m < n) {
int s = m; // Variable declared here... scoped to this if
s += recursivesum(m+2, n);
}
}
return s; // No such variable in scope!
}
You could use:
public static int recursivesum(int n, int m) {
int s = 0; // See note below
if (n < m) {
s = n + recursivesum(n+2, m);
} else {
if (m < n) {
s = m + recursivesum(m+2, n);
}
}
return s;
}
We have to give s
an explicit initial value, because you currently don't have any code handling the case where n
and m
are equal. It's not clear what you want to do then.
Another alternative is to return from the if
statements, just as you do in iterativesum
... although you'll again need to think about what to do if m == n
:
public static int recursivesum(int n, int m) {
if (n < m) {
// You don't even need an s variable!
return n + recursivesum(n+2, m);
} else if (m < n) {
// Simplified else { if { ... } } to else if { .... }
return m + recursivesum(m+2, n);
} else {
// What do you want to return here?
}
}
Note that you've got the same problem in iterativesum
- the compiler should be complaining at you at the moment that not all paths return a value. What do you expect iterativesum(3, 3)
to do?
See more on this question at Stackoverflow