簡體   English   中英

For循環中的Java數組索引超出界限異常

[英]Java Array Index Out of Bounds Exception in For-loop

我正在制作一個對輸入的數字運行公式的程序。 輸入中的第一個整數描述行數,即公式中要使用的整數。 我正在通過計算答案並將其推入數組來解決這一問題。 但是,我在一個for循環中遇到了數組超出范圍的異常,我不知道為什么。

這是我的主要方法:

    public static void main(String[] args) {
    Scanner scan = new Scanner (System.in);
    int[] nums = {};
    int lines = scan.nextInt();
    for(int i = 0; i < lines; i++){
        nums[i] = potFormula(scan.next());
    }
    System.out.println(nums);
}

數組具有固定大小,一旦分配就無法更改。 您正在將nums初始化為{} ,這是一個空數組。 它的大小將始終為零。

相反,您可以使用:

int lines = scanner.nextInt();
int[] nums = new int[lines];

您的數組太小(它的元素為零)。 這是解決此問題的一種方法:

int lines = scan.nextInt();
int[] nums = new int[lines];

因為您事先知道大小,所以這種方法有效。 如果沒有,則可以使用ArrayList<Integer> 陣列列表具有按需增長的能力。

您需要將nums數組初始化為行的長度,

像這樣:

public static void main(String[] args) {
    Scanner scan = new Scanner (System.in);
    int lines = scan.nextInt();
    int[] nums = new int[lines];
    for(int i = 0; i < lines; i++){
        nums[i] = potFormula(scan.next());
    }
    System.out.println(nums);
}

暫無
暫無

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

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