次のような単純なものを書く場合:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter array size: ");
int x = sc.nextInt();
int [] anArray;
int index = 100;
anArray = new int[x];
for (int i=0; i<=x; i++){
anArray[i] = index;
index += 100;
System.out.println ("Element at index "+ i + ": " + anArray[i]);
}
}
}
Netbeans はコードを適切にコンパイルして実行しますが、出力は次のようになります。
run:
Please enter array size:
12
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Element at index 10: 1100
Element at index 11: 1200
at Practice.main(Practice.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
私にはどちらがおかしいと思われます..コードの途中で例外がスローされるのはなぜですか? そして最後に終わった?
そして、それは 21 行目を指しています: anArray[i] = index;
正直なところ、大きな問題ではありません..私はただ遊んでいて、Javaのいくつかの基本を確認しているだけです(しばらく経ちました...)。実際には、私が意図したとおりに機能しているように見えるからです。
ありがとうございました!