I'm getting an error message as NoSuchElementException when I tried to take input using Scanner
in my program. So, please help because I'm beginner with it.
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
LinkedList list = new LinkedList();
list = create(list);
printList(list);
System.out.println("Enter 1 for insertion at the beginning : ");
System.out.println("Enter 2 for insertion at the end : ");
System.out.println("Enter 3 for insertion at the in between : ");
System.out.print("Enter choice : ");
int choice;
choice = Sc.nextInt();
switch (choice) {
case 1:
list = insertFirst(list);
printList(list);
break;
case 2:
list = insertLast(list);
printList(list);
break;
case 3:
list = insertMiddle(list);
printList(list);
break;
default:
System.out.println("Enter a valid choice.");
break;
}
Sc.close();
printList(list);
}
Actually, it is a basic Linked List implementation program with all its methods such as :
Insertion
deletion
searching
sorting,etc
Code for create method :
public static LinkedList create(LinkedList list){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements to be entered : ");
int n = sc.nextInt();
while(n-- > 0){
System.out.print("Enter data : ");
int data = sc.nextInt();
Node newNode = new Node(data);
if(list.head == null){
newNode.next = list.head;
list.head = newNode;
}
else{
Node temp = list.head;
while(temp.next != null){
temp = temp.next;
}
temp.next = newNode;
}
}
sc.close();
return list;
}
Output for the above code :
Enter the number of elements to be entered : 5
Enter data : 1
Enter data : 2
Enter data : 3
Enter data : 4
Enter data : 5
Linked List : 1 --> 2 --> 3 --> 4 --> 5
Enter 1 for insertion at the beginning :
Enter 2 for insertion at the end :
Enter 3 for insertion at the in between :
Enter choice : Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:941)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at LinkedList.main(LinkedList.java:29)