关于 java:蛮力算法问题

Brute Force Algorithm Issue

我已经查看了好几次代码,但我一直在以下行得到一个 Array Out of Bound:

sum = sum vectorArray[z]; }

谁能看出问题所在?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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]); }

    int max = -1;
    int sum;

    for (int x = 0; x < vectorArray.length; x++) {
        for (int y = x; x < vectorArray.length; y++) {
        sum = 0;
            for (int z = x; z <= y; z++) {
                sum = sum + vectorArray[z]; }
                max = Math.max(max, sum);
        } }
    System.out.println("The max:" +  max);
    }
}


在 for 循环中将 x 更改为 y

1
2
3
4
5
6
  for (int y = x; y < vectorArray.length; y++) {

                  ^
 sum = 0;
            for (int z = x; z <= y; z++) {
                sum = sum + vectorArray[z]; }