0

我一遍又一遍地查看代码,但似乎无法摆脱这个错误。我究竟做错了什么?我在粗体字处出现错误。

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;
        }
    }
}
4

2 回答 2

0

您正在访问数组中超出范围的位置 n+1。尝试更改以下行:

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

至:

for (int i = 0; i < n; i++)
于 2013-09-14T21:35:48.827 回答
0

一般来说,我认为它建议做这样的事情,以防在数组初始化后 n 发生变化,并且更明显的是你的代码在做什么(而且你再也不必担心这种异常):

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

于 2013-09-14T21:38:22.417 回答