Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

請問一下java顯示結果問題

import java.util.*;

public class array {

public static void main(String[] args) {

int A[]=new int[4];

System.out.println("number:");

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

System.out.print(A[i]+" ");

}

System.out.println();

Arrays.fill(A,1);

System.out.println("number:");

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

System.out.print(A[i]+" ");

}

System.out.println();

}

}

這是我照範例寫來測試的 但是結果卻是只輸出一半

我全不懂為甚麼? 我編譯都有過阿

是我設定不對 還是用法不對?

結果輸出是

number:

0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

at array.main(array.java:8)

但是我要的結果應該是全部都要出來才對阿 真詭異

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    因你設的int A[]=new int[4];

    代表int [] A 中有4個元素~~但A.length是為度 由0 開始 到3 索引值只有到3

    所以程式中 兩個for迴圈 中 不可以打成 i<=A.length~~因你後面還會有i++的動作~~如果 i = A.length 再 i++ ,就超出陣列索引值範圍才會拋出例外異常

    你須將兩個for迴圈中的 i<=A.length 改成 i < A.length 這樣就可以執行顯示如下

    number:

    0 0 0 0

    number:

    1 1 1 1

    Source(s): 加菲貓
Still have questions? Get your answers by asking now.