gpt4 book ai didi

java - 蛮力算法问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:09 26 4
gpt4 key购买 nike

我已经多次查看代码,但我总是在以下行中得到一个 Array Out of Bound:

sum = sum + vectorArray[z];

谁能看出哪里出了问题?

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

  for (int y = x; y < vectorArray.length; y++) {

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

关于java - 蛮力算法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com