簡體   English   中英

超出范圍異常錯誤

[英]Out of Bounds Exception Error

我一遍又一遍地看代碼,但似乎無法擺脫這個錯誤。 我究竟做錯了什么? 我在加粗的行上遇到了錯誤。

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

您正在訪問數組中超出范圍的位置n + 1。 嘗試更改以下行:

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

至:

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

總的來說,我認為建議這樣做,以防初始化數組后再也沒有改變,並且代碼的作用更加明顯(再也不必擔心這種Exception):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM