I recieve this exception while putting code in the codingblocks editor, but dont get it in my eclipse
Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:96)
code For reference:
import java.util.Scanner;
class Node {
int data;
Node next;
// constructor
Node(int d) {
data = d;
next = null;
}
}
public class Main {
static void insertAtTail(Node head, int data) {
if (head == null) {
return;
}
Node tail = head;
while (tail.next != null) {
tail = tail.next;
}
tail.next = new Node(data);
}
static Node takeInput() {
Scanner scanner = new Scanner(System.in);
int d = scanner.nextInt();
// Check if -1 is entered before the first integer
if (d == -1) {
return null;
}
Node head = new Node(d);
while (true) {
d = scanner.nextInt();
if (d == -1) {
break; // Stop when -1 is encountered
}
insertAtTail(head, d);
}
return head;
}
static int kthNodeFromLast(Node head, int k) {
if (head == null || k <= 0) {
return -1;
}
Node slow = head;
Node fast = head;
// Move fast k nodes ahead
for (int i = 1; i <= k; i++) {
if (fast == null) {
// If k is greater than the length of the list
return -1;
}
fast = fast.next;
}
// Move both fast and slow until fast reaches the end
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow.data;
}
static void print(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = takeInput();
if (head == null) {
System.out.println("Linked list is empty.");
} else {
Scanner scanner = new Scanner(System.in);
int k = scanner.nextInt();
int kthValue = kthNodeFromLast(head, k);
if (kthValue != -1) {
System.out.println(kthValue);
} else {
System.out.println("Invalid k value or linked list is too short.");
}
}
}
}