当我编写此代码以提示用户输入了多少个数字时,我收到一条错误消息:"线程主要java.lang.arrayindexoutofboundsexception中的异常"
PS:请注意我使用了一个int + for循环数组来编写它。
import java.util.*;
public class Pr8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
//Prompt the user for how many numbers are going to be entered.
System.out.print("*Please write how many numbers are going to be entered: ");
int a = scan.nextInt();
int[] n = new int[a];
for (int i = 0; i < a; i++){
System.out.print("*Please enter an enteger: ");
n[a] = scan.nextInt();
}//for
}//main
}//Pr8
&#13;
答案 0 :(得分:3)
更改
n[a] = scan.nextInt();
到
n[i] = scan.nextInt();
a
不是仅包含a
个元素的数组中的有效索引。有效索引为0到a-1。