2

My code below has a exception error for:

YN = input.nextLine().charAt(0); //line 13

when it is run. The assignment is to make an array that is assigned 10 numbers from console, when I put in 10 numbers the run completes automatically and gives an error for line 13. Is there something wrong with line 13 or is the issue with something else?

(The array must be a normal array and not an arrayList)

import java.util.*;
import java.util.Arrays;

public class CountOccurrences {
    static Scanner input = new Scanner(System.in);
    static int[][] temp = new int[10][1];

    public static void main(String[] args) {
        char YN = 'y';

        while (YN == 'y') {
            run();
            System.out.print("Continue? (y or n)\t");
            YN = input.nextLine().charAt(0); // Line 13
        }
    }

    public static void run() {
        System.out.print("Enter the integers between 1 and 100: ");

        int[] numbersArray = new int[10];

        for (int i = 0; i < numbersArray.length; i++) {
            numbersArray[i] = input.nextInt();
        }

        for (int i = 0; i < numbersArray.length; i++) {
            Arrays.sort(numbersArray);
            System.out.println(numbersArray[i]);
        }
    }
}
Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
bill
  • 51
  • 8

1 Answers1

4

input.nextLine() could be an empty String, in which case input.nextLine().charAt(0) will give you that exception. You should check the length() of the String before calling charAt.

Now that I see you are using input.nextInt() to read the inputs in your run() method, what you have to do is add a input.nextLine() at the end of the run() method, to consume the end of the line that contains the final int.

You still have to check the length of the String you get in input.nextLine(), though, since the user may hit enter instead of hitting Y or N, which will result in the same exception.

Eran
  • 359,724
  • 45
  • 626
  • 694
  • @Tom: Out of curiosity, what makes you confident that it's a duplicate? Especially of [this question](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next-nextint-or-other-nextfoo-methods)? – Makoto Apr 06 '15 at 15:39
  • @Makoto Two things: the source of the problem and the solution. Or why do you think, it isn't a duplicate? – Tom Apr 06 '15 at 16:24