简体   繁体   中英

Recursion in Java: I'm having a problem with printing the result

Down below is my code. My problem is that if I try to use the method on an array I get an ArrayIndexOutOfBounds Exception and I have no idea why. Maybe someone can help.

public class Recursion {
    
        public static void main(String[] args) {
            
            int[] array = new int[] {3, 4, 7, 2, 6};
            stepSum(array);
            
        }
        
        public static void stepSum(int[] numbers) {
            if(numbers.length == 0) {
                return;
            } else if (numbers.length == 1) {
                System.out.println(numbers[0]);
            } else {
            int[] sumNumbers = new int[numbers.length - 1];
            for (int i = 0; i < numbers.length; i++) {
                sumNumbers[i] = numbers[i] + numbers[i+1];
            }
            stepSum(sumNumbers);
            }
            
            for (int number : numbers) {
                System.out.print(number + " ");
            }
            System.out.println();
            
        }
        
    }

numbers[i+1]

That is going to exceed the index the last time through the loop because i is the last valid index.

In your for loop replace numbers.length with sumNumbers.length

Because numbers.length is larger than the new sumNumbers.length it will end up always doing one iteration more than the sumNumbers.length. This won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM