我正在尝试在 Java
中执行以下程序我正在编写一个递归和迭代方法来计算 n
中所有奇数的总和至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)); } }
我收到错误无法找到符号-变量 enter code here
s。我不知道怎么了!有人可以帮忙吗?
最佳答案
这个方法有问题:
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!
}
您可以使用:
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;
}
我们必须给 s
一个明确的初始值,因为您当前没有任何代码处理 n
和 m
的情况是平等的。目前还不清楚你想做什么。
另一种选择是从 if
语句返回,就像在 iterativesum
中所做的那样...尽管您将再次需要考虑如果 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?
}
}
请注意,您在 iterativesum
中遇到了同样的问题 - 编译器此时应该向您提示并非所有路径都返回值。您期望 iterativesum(3, 3)
做什么?
关于java - 找不到符号-变量java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22630398/