简体   繁体   中英

java.lang.ArrayIndexOutOfBoundsException error

This runs smoothly from start to the first looping part, but when displaying the user input(on the second loop), the program stops and there is a message in the cmd:

(Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at 
CaseStudy2A.main(CaseStudy2A.java:17)

Code:

import java.util.Scanner;
public class CaseStudy2A {
    public static void main(String[] args) {
        Scanner inp = new Scanner (System.in);
        int inpNum;
        System.out.print("Enter Number: ");
        inpNum = inp.nextInt();

        int num[]=new int [inpNum];

        int accu;

        for(int x=1;x<=inpNum;x++) {
            System.out.print("\nNumber [" + x + "] : ");
            accu = inp.nextInt();

            num[x]=accu;
        }
        for(int x=1;x<=inpNum;x++)
            System.out.println(num[x] + " ");
    }
}

Array indexes starts from zero.

loop should be

   for(int x=1;x<inpNum;x++) {  

For example

consider inpNum= 5 then

 int num[]=new int [5]; //5 elements ,position 0,1,2,3,4

num[5] throws exception, since array initialized with 5 elements num[0] to num[4]

And also in remaining places, change the condition to x<inpNum from x<=inpNum

应该是for(int x=0;x<inpNum;x++) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM