使用数组+ for循环时“线程主java.lang.arrayindexoutofboundsexception中的异常”

时间:2014-11-07 13:03:56

标签: java arrays main

当我编写此代码以提示用户输入了多少个数字时,我收到一条错误消息:"线程主要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;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

更改

n[a] = scan.nextInt();

n[i] = scan.nextInt();

a不是仅包含a个元素的数组中的有效索引。有效索引为0到a-1。