下面代码报错,请修改public class computer { public static void main(String[] args) { int result = sum(5); System.out.println(result); } private static int sum(int sum){ int num = 0; if(num==1){ return 1; }else{ return num+sum(num-1); } } }
时间: 2023-12-12 22:02:01 浏览: 72
这段代码的问题在于 `num` 没有被赋值,所以默认值为 0,导致递归函数一直执行下去,直到抛出 StackOverflowError 异常。同时,递归函数也存在问题,因为递归条件写错了。
以下是修改后的代码:
```java
public class Computer {
public static void main(String[] args) {
int result = sum(5);
System.out.println(result);
}
private static int sum(int num) {
if(num == 1) {
return 1;
} else {
return num + sum(num-1);
}
}
}
```
修改后的代码中,将 `num` 的默认值改为了传入的参数 `num`,并且修改了递归条件,使得递归能够正确终止。
相关问题
完成下列代码interface ComputerAverage { public double average(double x[]);}class Gymnastics implements ComputerAverage { public double average(double x[]) { int count=x.length; double aver=0,temp=0; for(int i=0;i<count;i++) { for(int j=i;j<count;j++) { if(x[j]<x[i]) { temp=x[j]; x[j]=x[i]; x[i]=temp; } } } for(int i=1;i<count-1;i++) { aver=aver+x[i]; } if(count>2) aver=aver/(count-2); else aver=0; return aver; }}class School implements ComputerAverage { 【代码1】//重写public double average(double x[])方法,返回数组x[]的元素的算术平均}public class Estimator{ public static void main(String args[]) { double a[] = {9.89,9.88,9.99,9.12,9.69,9.76,8.97}; double b[] ={89,56,78,90,100,77,56,45,36,79,98}; ComputerAverage computer; computer=new Gymnastics(); double result= 【代码2】 //computer调用average(double x[])方法,将数组a传递给参数x System.out.print
以下是完成代码的方法:
```java
interface ComputerAverage {
public double average(double x[]);
}
class Gymnastics implements ComputerAverage {
public double average(double x[]) {
int count = x.length;
double aver = 0, temp = 0;
for (int i = 0; i < count; i++) {
for (int j = i; j < count; j++) {
if (x[j] < x[i]) {
temp = x[j];
x[j] = x[i];
x[i] = temp;
}
}
}
for (int i = 1; i < count - 1; i++) {
aver = aver + x[i];
}
if (count > 2)
aver = aver / (count - 2);
else
aver = 0;
return aver;
}
}
class School implements ComputerAverage {
//重写public double average(double x[])方法,返回数组x[]的元素的算术平均
public double average(double x[]) {
int count = x.length;
double sum = 0;
for (int i = 0; i < count; i++) {
sum += x[i];
}
return sum / count;
}
}
public class Estimator {
public static void main(String args[]) {
double a[] = { 9.89, 9.88, 9.99, 9.12, 9.69, 9.76, 8.97 };
double b[] = { 89, 56, 78, 90, 100, 77, 56, 45, 36, 79, 98 };
ComputerAverage computer;
computer = new Gymnastics();
double result1 = computer.average(a); //computer调用average(double x[])方法,将数组a传递给参数x
System.out.print("Gymnastics average: " + result1);
computer = new School();
double result2 = computer.average(b); //computer调用average(double x[])方法,将数组b传递给参数x
System.out.print("School average: " + result2);
}
}
```
在`School`类中,重写了`average`方法,计算并返回传递给该方法的数组`x[]`的算术平均值。在`Estimator`类的`main`方法中,先使用`Gymnastics`类计算数组`a[]`的平均值,再使用`School`类计算数组`b[]`的平均值,并将结果打印出来。
阅读全文