Reputation: 21
I am trying to take user input first on how many items he wants to add and then adding them in the reverse order(appending). Next is trying to take two inputs: adding some integer to a specific position but it is throwing runtime error. Also, is there anyway to make this code more readable or efficient?
Error:
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "<local3>" is null
at Solution.append(Solution.java:37)
at Solution.main(Solution.java:79)
Input:
3
16
13
7
1
2
Expected Output: 16 13 1 7
Output: ~ no response on stdout ~
Code:
public class Solution{
Node head;
static class Node{
int data;
Node next;
Node(int d) {
this.data = d;
next = null;
}
}
public void append(int newData){
Node newNode = new Node(newData);
if(head == null){
head = new Node(newData);
return;
}
newNode.next = null;
Node last = head;
while(last != null) {
last = last.next;
}
last.next = newNode;
return;
}
public void printList(){
Node temp = head;
while(temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
}
public void insertAt(Node head, int position, int data){
Node node = new Node(data);
if(head == null) {
head = new Node(data);
return;
}
else if(position == 0) {
node.next = head;
head = node;
return;
}
else{
Node current = head;
for( int j = 0; j < position-1; j++){
current = current.next;
}
node.next = current.next;
current.next = node;
return;
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Solution llist = new Solution();
int n = sc.nextInt(); sc.nextLine();
for( int i = 0; i < n; i++) {
int element = sc.nextInt();
if(sc.hasNextLine()) sc.nextLine();
llist.append(element);
}
int data = sc.nextInt(); sc.nextLine();
int position = sc.nextInt(); sc.nextLine();
llist.insertAt(llist.head, position, data);
llist.printList();
}
}
Upvotes: 2
Views: 658
Reputation: 1648
Exception message points to the problem:
Node last = head;
while(last != null) { // loop ends when last == null
last = last.next;
}
last.next = newNode; // accessing property of a null object -> NPE
While loop most probably should be:
while(last.next != null)
Upvotes: 0
Reputation: 11
I dont fully understand what you are trying to do. But I would sugget to you maybe to do some priting at your main so you can follow the input from the user. From the errors kind I can guess that maybe the user enter some data to the node and some where at your code the program treats this variable as an index
So at first just make your main something like that:
Scanner sc = new Scanner(System.in);
Solution llist = new Solution();
System.out.println("How many items");
int n=sc.nextInt();
for( int i = 0; i < n; i++) {
System.out.println("Enter the element");
int element = sc.nextInt();
System.out.println("Enter the index");
int index=sc.nextInt();
llist.append(element);
}
and keep going with the rest of your code
Upvotes: 1