这是我的代码到目前为止,但是当我运行它并为n输入一个值时,程序以“数字总和为:”结束,这就是全部。无论我输入什么价值,都不会改变,你能帮我弄清楚我做错了吗?
import java.util.Scanner;
class addNum
{
//A method for Adding
public static int addNum (int arr[], int n)
{
int x = 0;
if (n > arr.length)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
x = arr[n-1] + addNum(arr, n);
return n;
}
}
public static void main(String args[])
{
int n = 0;
int arr[] = {1,2,3,4,5,6,7};
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.print("Sum of numbers is:");
addNum(arr, n);
System.out.println();
}
}
答案 0 :(得分:1)
尝试将其更改为
System.out.println(addNum(arr, n));
所以实际上有些东西被退回并打印
并且存在错误
x = arr[n-1] + addNum(arr, n);
return x; // not n
答案 1 :(得分:1)
addNum(arr, n);
这只是一个函数调用addNum(param1,param2)。
它只会返回值,而不是打印出值。 因此,您必须打印出该值才能看到它。
System.out.println(addNum(arr, n));
如Siren P.所述,
答案 2 :(得分:0)
试试这个:
public static int addNum (int arr[], int n)
{
int x = 0;
if (n > arr.length)
{
return 0;
}
else if (n == 1)
{
//When n == 1, you want to return the first element of your array and not 1
return arr[0];
}
else
{
//As you go deeper into recursion, you break your problem into a smaller problem.
//Therefore, when calling addNum again, you pass n-1 and not n, as now you want to add remaining n-1 numbers
x = arr[n-1] + addNum(arr, n-1);
// you want to return your sum x and not n
return x;
}
}
public static void main(String args[])
{
int n = 0;
int arr[] = {1,2,3,4,5,6,7};
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.print("Sum of numbers is:");
//Your addNum method returns an int, so you want to save it in a variable and then print it
int x = addNum(arr, n);
System.out.println(x);
}