xxxxxxxxxx
// Short answer:
// The close function causes the problem.
// Do not close the Scanner.
// You may want to use one single Scanner
// for the whole program.
// Can close the scanner when no further
// input needed.
// Long answer:
Scanner scan1 = new Scanner(System.in);
String name = scan1.nextLine();
scan1.close(); // Problem is here
Scanner scan2 = new Scanner(System.in);
String name = scan2.nextLine();
scan2.close();
// Calling the close function of the Scanner object
// will result in closing "System.in" and once
// closed, not sure it can be opened again.
// So you can have one scanner at beginning
// and passing that along everywhere as a parameter,
// public class or something.
// At end of the program or whenever there was
// no more need for inputs, the Scanner can be
// closed.
xxxxxxxxxx
/*
NoSuchElementException is thrown when we try to access an element
that does not exist in a list through an iterator, as illustrated below.
*/
import java.util.ArrayList;
import java.util.List;
public class NoSuchElementExceptionDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
// The below statement generates a NoSuchElementException
// The iterator cannot access the non-existent element
System.out.println(list.iterator().next());
}
}