简体   繁体   中英

Out of Bounds Exception Error

I looked at the code over and over but I can't seem to get rid of this error. What am I doing wrong? I'm getting an error at the line I bolded.

import java.util.Scanner;
import java.math.*;

public class HW1 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        // The numbers for n are not relevant
        System.out.println("Please enter a number for the length of n.");
        int n = input.nextInt();

        // Creates an array with n values
        int[] vectorArray = new int[n];

        // Inputs random numbers into the array ranging from -100 to 100.
        int dummy;
        int temp = 0;

        // Loop to generate negative and positive numbers into the array
        for (int i = 0; i <= n; i++) {

            dummy = (int)(Math.random()*2);
            if (dummy == 0) { 
                temp = -1; 
            } else {
                temp = 1; 
            } 

            **vectorArray[i] = ((int)(Math.random()*101)) * temp;**
            System.out.println(vectorArray[i]); }

        // Algorithm 1 - Brute force O(n^3)

        int max = -1;
        int sum;
        }
    }
}

You are accessing position n+1 in the array which is out of bounds. Try changing the following line:

for (int i = 0; i <= n; i++)

To:

for (int i = 0; i < n; i++)

总的来说,我认为建议这样做,以防初始化数组后再也没有改变,并且代码的作用更加明显(再也不必担心这种Exception):

for (int i = 0; i < vectorArray.length; i++)

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