BAS
BAS

Reputation: 155

"exception in thread main java.lang.arrayindexoutofboundsexception" when using an array + for loop

when I wrote this code to prompt the user for how many numbers are going to be entered, I got an error saying: "exception in thread main java.lang.arrayindexoutofboundsexception"

PS: note that I used an array of int + for loop to write it.

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

Upvotes: 0

Views: 1038

Answers (1)

Eran
Eran

Reputation: 393956

Change

n[a] = scan.nextInt();

to

n[i] = scan.nextInt();

a is not a valid index in an array that only has a elements. The valid indices are 0 to a-1.

Upvotes: 3

Related Questions