简体   繁体   中英

Array Index Out Of Bounds Exception

The problem:

a program that updates a list of students' grades after the end of drop period. The program should reads from the user number of students who dropped and their indexes, and then the program should copies the remaining student's grades to new array. In addition, the program should display both the original and the updated list. [Hint: the new array must have suitable length equivalents to number of remaining students]

my code:

public class Q5{
  static Scanner scan = new Scanner (System.in);
  public static void main (String args[]){

    double [] list={1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
    System.out.println("enter number of students who dropped:");
    int num=scan.nextInt();
    double [] list2 = new double [num];

    System.out.println("Enter index Of  the student who dropped ");
    for (int j=1 ; j<=num ; j++)
    {
      System.out.println("student" + j + ":");
      int index=scan.nextInt();
      list[index]=0;
    }

    int  j=0;
    for(int i=0; i<list.length ; i++)
    if (list[i]!=0)
    {
      list2[j]=list[i];
      j++;
    }
    System.out.print("The original list : " );
    for(int i=0; i<list.length ; i++)
    System.out.print(list[i] + " " );

    System.out.print("remaining students " );
    for(int i=0; i<list2.length ; i++)
    System.out.print(list2[i] + " " );
  }
}

what is the problem ? it is not working !!! in Line 16 it says :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Q5.main(Q5.java:23)

how I can correct this

That's because of the size of your list2 .

You shouldn't set its size to num , but rather to the size of the original list. Because the list2 is going to contain just as many elements as the original list . You need the num only to fetch that many inputs from the user and assign those indexes with the value 0 .

double[] list2 = new double[list.length]; // This should be the size of your list2

If you don't need to keep the original size, then you need to subtract the num from the original size, as suggested by @Joetjah .

double[] list2 = new double[list.length - num]; // This should be the size of your list2

Your code will fail if the value entered by user is out of bounds for the array :

int index=scan.nextInt();
list[index]=0; // This may fail. Value entered by the user may exceed the array length

Pseudo-code:

You start of with 10 students. Say you want to drop 2 students. That means you set the list2 size to 2.

Next thing you do, is trying to add all the students (10) from list to list2 . But, list2 is too small for this. Thus you get your Exception.

What you want, is this:

double [] list2 = new double [list.length - num];

Guess that problem with predefined array 'list'.

Step 1: Created the list with one of the initializing ways. Here the size is fixed.

Step 2: Took input from user : lets assume it is 11.

list doesn't need to contain the size given as input.

You initialize list2 with wrong size.

You get from the user number of dropped students and then try to put in list2 all the remaining students.

double [] list2 = new double [list.length - num];

Its working fine

import java.util.Scanner;

public class Q5 {
    static Scanner scan = new Scanner(System.in);

    public static void main(String args[]) {

        double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        System.out.println("enter number of students who dropped:");
        int num = scan.nextInt();
        double[] list2 = new double[num - 1]; // should be num-1

        System.out.println("Enter index Of  the student who dropped ");
        for (int j = 0; j < num; j++) {
            System.out.println("student" + j + ":");
            int index = scan.nextInt();
            list[index] = 0;
        }

        int j = 0;
        for (int i = 0; i < num; i++) {
            if (list[i] != 0) {
                list2[j] = list[i];
                j++;
            }
        }
        System.out.print("The original list : ");
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }

        System.out.print("remaining students ");
        for (int i = 0; i < list2.length; i++) {
            System.out.print(list2[i] + " ");
        }
    }
}

output is

 enter number of students who dropped:
    2
    Enter index Of  the student who dropped 
    student0:
    1
    student1:
     2
    The original list : 1.0 0.0 0.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 remaining students 1.0 

This will remove the exception you got. From next time you don't use static values.

Edit: It is not a good practice to assign values to any variable by yourself. As the array is having size of 10. If user enters more than 10 students dropped then it will cause a problem.

import java.util.*;

public class Q5 {
    static Scanner scan = new Scanner(System.in);

    public static void main(String args[]) {

        double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        System.out.println("enter number of students who dropped:");
        int num = scan.nextInt();
        double[] list2 = new double[list.length-num]; // should be num-1

        System.out.println("Enter index Of  the student who dropped ");
        for (int j = 0; j < num; j++) {
            System.out.println("student" + j + ":");
            int index = scan.nextInt();
            list[index] = 0;
        }

        int j = 0;
        for (int i = 0; i < list.length; i++) {
            System.err.println(""+list[i]);
            if (list[i] > 0) {

                list2[j] = list[i];
                j++;
            }
        }
        System.out.print("The original list : ");
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }

        System.out.print("remaining students ");
        for (int i = 0; i < list2.length; i++) {
            System.out.print(list2[i] + " ");
        }
    }
}

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