写了一个用递归方法来得到数组中最大值的小程序,请高手指出其中的不足!
public class TestDi {

int[] a = new int[]{3,6,9,4,1,21,7,5};
int temp = 0;

public static void main(String[] args) {

int num =0;
TestDi t = new TestDi();
t.getD(num);
}

public  void getD(int num) {

if(temp==a.length-1) {
System.out.println(num);
}

if(temp<a.length-1&&num<a[temp]) {
num = a[temp];
temp++;
getD(num);
}else if(temp<a.length-1&&num>=a[temp]){
temp++;
getD(num);
}
}}

解决方案 »

  1.   

    就java的方法设计来,get方法一般都会有返回值的。这点注意下。
      

  2.   


    public class Test{
    private static int[] array = {3,6,9,4,1,21,7,5};
    private static int result = array[array.length - 1];
    public static void main(String[] args){    
    int max = getMax(array.length - 1);
    System.out.println(max);
    }
    public static int getMax(int index){
    if(index == -1){
    return result;
    } int temp = array[index]; if(temp > result){
    result = temp;
    } return getMax(index - 1);
    }
    }