1

I'm getting this error java.util.NoSuchElementException from my code below and I can't figure out why. I'm attempting to write a code that reads an integer, a list of words, and a character. The integer signifies how many words are in the list. The output of the program is every word in the list that contains the character at least once.

       public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] arr = new String[n];
        for(int i = 0; i < n; ++i) {
            arr[i] = in.next();
        }
        char ch = in.next().charAt(0); //line that launches the error
        for(int i = 0; i < n; ++i) {
            if(arr[i].contains(""+ch)) {
                System.out.println(arr[i]);
            }
        }
    }
Rozay
  • 25
  • 4
  • 2
    Maybe you read an empty line? Yeah, you do. See https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – Johannes Kuhn Sep 22 '19 at 21:49
  • 2
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – oleg.cherednik Sep 22 '19 at 21:49
  • Thanks for pointing me in that direction. I'm still confused on what the problem is though. Does the real problem lie with `arr[i] = in.next();` ? – Rozay Sep 22 '19 at 22:15

0 Answers0