我一遍又一遍地看着代码,但我似乎无法摆脱这个错误。我究竟做错了什么?我在加粗的那一行收到错误。
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;
}
}
}
答案 0 :(得分:0)
您正在访问数组中超出界限的位置n + 1。 尝试更改以下行:
for (int i = 0; i <= n; i++)
要:
for (int i = 0; i < n; i++)
答案 1 :(得分:0)
一般来说,我认为在数组初始化之后,如果n发生变化,我建议做这样的事情,并且你的代码做得更明显(再加上你再也不用担心这种异常了) ):
for (int i = 0; i < vectorArray.length; i++)