0

Hope this is better. I am writing a java assignment to implement a sorting technique. I used a scanner object within a loop to input user data to be sorted. However the scanner object continues to read data after array is filled and an index out of bounds error is shown. How do I deal with this.

public static void set1(int N)
{
    int i,c,e,f;
    double a,b;
    int[] arr1 = new int[N];
    int[] arr2 = new int[N];
    System.out.println("Please enter numbers to be sorted");

    for(i=0;i<=N;i++)
    {
        Scanner Secondin = new Scanner(System.in);
        arr1[i] =  Secondin.nextInt();
    }
}
Mischiefz
  • 127
  • 16
Jed Anim
  • 1
  • 1

2 Answers2

0
  1. From 0 to and including N is too much. a new int[5] has slots 0, 1, 2, 3, and 4. That's 5 slots. arr1[5] is an ArrayIndexOutOfBoundsException because that'd be the 6th slot. Try for (int i = 0; i < N; i++) instead (note, < instead of <=).

  2. Don't keep making scanners. Make 1 scanner, once, and keep using it.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
-3

Inside the for loop at the end, try this code:

if (i == N) {
break;
}

This will break out of the for loop as soon as you reach the limit = N.

uncommon_breed
  • 172
  • 2
  • 2
  • 13
  • You are doing it wrong. If you want your array to be of size N and if you start reading from index 0, you need to read only until N-1. As soon as your index reaches the size of N, you need to exit out of the loop. Try the below: for(i=0;i – uncommon_breed Mar 15 '19 at 21:06