Adding Numbers to a Range - java

I'm making a program where I can add an Integer sequence to a Range. I'm having trouble adding this values to the Range. It should run the method addNodeAfter, but it does nothing.
Then when I want to display the Range I get a NullPointerException one this line:
for (int i = 1; i <= manyNodes; i++){
Any tips?
Main:
public class PDEMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a start number: ");
Integer startNum = input.nextInt();
System.out.print("Enter end number: ");
Integer endNum = input.nextInt();
System.out.print("Enter increment: ");
Integer increment = input.nextInt();
Range obj = new Range(startNum, endNum, increment);
System.out.println(obj);
obj.display();
}
}
Range:
public class Range implements Cloneable {
private Integer data; // holds the data
private Range link; //holds the link
Range head; //refers to head of linked list
private Integer manyNodes;
private Integer startValue;
private Integer endValue;
private Scanner input;
public Range(Integer data, Range link){
this.data = data;
this.link = link;
}
public Range(Integer data, Range link, Range head) {
this.data = data;
this.link = link;
this.head = head;
manyNodes++;
}
public Range(Integer start, Integer end,Integer increment){
if(start == null){
startValue = 0;
}
if(increment == null){
if(start < end){
increment++;
}else{
increment--;
}
}
for (int i = start; i <= end; i+= increment){
addNodeAfter(i);
System.out.println(i);
}
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public Range getLink() {
return link;
}
public void setLink(Range link) {
this.link = link;
}
public Range getHead() {
return head;
}
public void setHead(Range head) {
this.head = head;
}
public void addNodeAfter(Integer element){
this.link = new Range(element, this.link);
}
public void display(){
Range cursor = head;
for (int i = 1; i <= manyNodes; i++){ // NPE on this line
System.out.print(cursor.getData() + " ");
cursor = cursor.getLink();
}
System.out.println("");
}
}

You have defined manyNodes as an Integer, not an int. This means that its default value is null, not 0, and you never set the value anywhere in your code.
When you try to loop using it as the control variable in your display() method, the JVM is going to throw an NPE when it tries to unbox the null.
A quick fix would be to change the type to int:
private int manyNodes;
This will solve the immediate NPE, but still not display anything, since you never actually increment manyNodes in the constructor you're calling. This means that the for-loop in your display() method falls through and never actually prints any of the data.
I would recommend getting rid of head and manyNodes altogether, and re-writing your display() method along the lines of:
public void display() {
Range cursor = getLink();
while (cursor != null) {
System.out.print(cursor.getData() + " ");
cursor = cursor.getLink();
}
System.out.println("");
}
Note that this will output the data "backwards" because of the way you add things in this constructor:
public static void main(String[] args) throws Exception {
Range obj = new Range(1, 10, 1);
obj.display(); // prints 10 9 8 7 6 5 4 3 2 1
}
You might want to take a look at an existing linked-list implementation to get a better idea how they are normally written.

Related

Count occurence in linklist using recursive in java

I insert some elements in Node in java,displaying element also working fine.But when i search any element occurrence using recursive its always return value zero .Sorry wrong for my english.I am new in data structure implementation in java . Thanks
public class pal{
private static Node head;
private static class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
}
public static void addToTheLast(Node node) {
if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
public static void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
int no ;
Node head = null ;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Element ");
no = sc.nextInt();
for(int i = 0 ;i< no; i ++){
System.out.print("Enter Element ");
int a = sc.nextInt();
if(head == null){
head = new Node(a);
addToTheLast(head);
}else{
addToTheLast(new Node(a));
}
}
printList();
System.out.print("Enter search key");
int key = sc.nextInt();
int yo = count(head,key);
System.out.print(String.valueOf(yo));
}
public int count (Node head,int key){
int cnt = 0;
if(head == null){
return cnt;
}else{
if(temp.value == key)
cnt++;
count(temp.next,key)
}
return cnt;
}
}
Always retun value 0 if element is present in linklist
Your code does not compile as you are referring to a variable temp within count method, but it does not exist.
You have to replace temp with head.
Also, you are losing the cnt value in your recursive call. You are incrementing cnt which is a local variable.
I have modified the code to pass along the value of count as a parameter.
public static int count(Node head, int key, int count){
if(head == null){
return count;
} else {
if(head.value == key) {
return count(head.next, key, count + 1);
} else {
return count(head.next, key, count);
}
}
}
If you don't want the callers of count to pass 0 to the last parameter (as count(head, key, 0)), make it a private method and make the public search method call this (I prefer this method as it is cleaner)
public static int count(Node head, int key) { //main method calls this
return call(head, key, 0); //calls the above method
}

Adding a number in between a Range

I have made a program that takes a user's input for start number, end number, and an increment. This is added to a Range (linked-list). I want to add a number that the user inputted to this Range and put the inputted number in between each number.
Main:
public class PDEMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a start number: ");
Integer startNum = input.nextInt();
System.out.print("Enter end number: ");
Integer endNum = input.nextInt();
System.out.print("Enter increment: ");
Integer increment = input.nextInt();
Range obj = new Range(startNum, endNum, increment);
obj.display();
System.out.print(" Enter 1 for take:\n "
+ "Enter 2 for drop:\n "
+ "Enter 3 for repeat:\n "
+ "Enter 4 for interpose: ");
Integer number = input.nextInt();
if(number == 1) {
obj.take();
}
if(number == 2) {
obj.drop();
}
if(number == 3) {
obj.repeat();
}
if(number == 4) {
obj.interpose();
}
}
}
Range:
public class Range implements Cloneable {
private Integer data; // holds the data
private Range link; //holds the link
private Range head; //refers to head of linked list
private Integer startValue;
private Integer endValue;
private Scanner input;
public Range(Integer data, Range link) {
this.data = data;
this.link = link;
}
public Range(Integer data, Range link, Range head) {
this.data = data;
this.link = link;
this.head = head;
}
public Range(Integer start, Integer end,Integer increment) {
if(start == null) {
startValue = 0;
}
if(increment == null) {
if(start < end) {
increment++;
} else {
increment--;
}
}
for (int i = start; i <= end; i+= increment) {
addNodeAfter(i);
}
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public Range getLink() {
return link;
}
public void setLink(Range link) {
this.link = link;
}
public Range getHead() {
return head;
}
public void setHead(Range head) {
this.head = head;
}
I have the following code for this interpose method:
public void interpose() {
System.out.println("What number would you like to interpose? ");
Integer answer = input.nextInt();
Range cursor = head;
for (int i = 0; i <= answer; i++) {
System.out.print(cursor.getData() + " ");
this.link = new Range(answer, this.link);
cursor = cursor.getLink();
}
System.out.print("New Range: ");
display();
modify();
anotherRange();
}
I get a NullPointerException at Integer answer = input.nextInt();
Any tips on why I get this Exception and also if my logic is correct?
Try to add Scanner class into interpose() method like this:
Scanner input = new Scanner(System.in);
Integer answer = input.nextInt();

Sorting a linked list of names alphabetically

Hey guys I am trying to sort a linked list alphabetically by multiplying the first 3 letters together. The way it works is that the first letter would take 26^2, the second letter would be 26^1 and the third would be 26^0. When i run the program it is giving me the same sum for say the name "lala" and "francis". If anybody could help me see what is wrong with the code, it will be greatly appreciated!
LinkedListNode class: (contains the getSum method)
public class LinkedListNode
{
public String data;
public LinkedListNode next;
public long sum;
public LinkedListNode(String data)
{
this.data = data;
this.next = null;
this.sum = getSum(data);
}//end node
public long getSum(String line)
{
int i;
long sum = 0;
String s = null;
char a;
for(i=0; i < 3; i++)
{
int j = 2;
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, j);
//Return the value of the number 4 to be the power of 3 (4*4*4): Math.pow(4,3);
j--;
}//end for
return sum;
}//end getSum
public long getSum()
{
return sum;
}//end getSum
public String getData()
{
return data;
}//end getData
public void setData(String data)
{
this.data = data;
}//end setData
public LinkedListNode getNext()
{
return next;
}//end node
public void setNext(LinkedListNode next)
{
this.next = next;
}//end setNext
}//end class node
LinkedList class: (has other methods for the list)
public class LinkedList {
public LinkedListNode front;
public LinkedList() {
this.front = null;
}
public void insertBack(String data)
{
if(front == null){
front = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = front;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}//end insertBack
public void addAfter(LinkedListNode spot, String data)
{
LinkedListNode newNode;
newNode = new LinkedListNode(data);
newNode.next = spot.next;
spot.next = newNode;
}//end addAfter
public void addBefore(LinkedListNode spot, String data)
{
}//end addBefore
public void deleteAfter(LinkedListNode spot)
{
LinkedListNode nextNode;
nextNode = spot.next;
spot.next = nextNode.next;
}//end deleteAfter
public String showList()
{
int i = 0;
String retStr = "The nodes in the list are:\n";
LinkedListNode current = front;
while(current != null){
i++;
retStr += "Node " + i + " is: " + current.getData() + " and the sum is: " + current.getSum() + "\n";
current = current.getNext();
}
return retStr;
}
public LinkedListNode findTail()
{
LinkedListNode current = front;
while(current.getNext() != null)
{
current = current.getNext();
}
return current;
}//end findTail
}
fileIn class:
import java.util.Scanner;
import java.io.*;
public class fileIn
{
LinkedListNode front;
LinkedList myList = new LinkedList();
String fname;
public static void main(String[] args)
{
fileIn f = new fileIn();
}//end main
public fileIn()
{
getFileName();
readFileContents();
System.out.print(myList.showList());
}//end namesLinkedList
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try
{
in = new DataInputStream(new FileInputStream(fname));
looping = true;
while(looping)
{
/* Get a line of input from the file. */
if (null == (line = in.readLine()))
{
looping = false;
/* Close and free up system resource. */
in.close();
}//end if
else
{
myList.insertBack(line);
j = 0;
len = line.length();
}//end else
} /* End while. */
} /* End try. */
catch(IOException e)
{
System.out.println("Error " + e);
} /* End catch. */
}//end readFileContents
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
}//end getFileName
}//end class namesLinkedList
for (i = 0; i < 3; i++) {
int j = 2;
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, j);
j--;
}
You're getting the same result because the exponent is always 2. This leads to the same value for fra (15×262 + 27×262 + 10×262 = 35,152) and lal (21×262 + 10×262 + 21×262 = 35,152). Why is this?
The variable j is declared inside the loop instead of outside. The decrement at the end has no effect since it starts over at 2 at the beginning of each iteration.
You should move the declaration out of the loop:
int j = 2;
for (i = 0; i < 3; i++) {
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, j);
j--;
}
Or you could replace j with 2 - i and get rid of the extra variable entirely.
for (i = 0; i < 3; i++) {
a = line.charAt(i);
sum += Character.getNumericValue(a) * Math.pow(26, 2 - i);
}
Looks like your math is wrong. Character.getNumericValue(a) will not return you a value between 0 and 25 like you seem to think.
Just make a custom Comparator class if you want to sort based on fist 3 letters and use that.
Edit: I was wrong about how getNumericValue works, but the math is still wrong (see comment below).

I can't figure out how to fix error NullPointerException

I think that smallIndex, index, and temp all have values, so Im not sure why I am getting the error. Can anyone explain to me why this is happening? The error message is:
Exception in thread "main" java.lang.NullPointerException
public class LinkedList
{
public class LinkedListNode
{
public int info;
public LinkedListNode next;
public LinkedListNode back;
public LinkedListNode()
{
info = 0;
next = null;
back = null;
}
public LinkedListNode(int item)
{
info = item;
next = null;
back = null;
}
public void displayInfo()
{
System.out.print(info + " ");
}
}
protected int count;
protected LinkedListNode first;
protected LinkedListNode last;
public LinkedList()
{
first = null;
last = null;
count = 0;
}
public void initializeList()
{
first = null;
last = null;
count = 0;
}
public boolean isEmpty()
{
return (first == null);
}
public int length()
{
return count;
}
public void print()
{
LinkedListNode current = first;
while (current != null)
{
current.displayInfo();
current = current.next;
}
}
public void insertNode(int insertItem)
{
LinkedListNode newNode = new LinkedListNode(insertItem);
if (isEmpty())
{
first = newNode;
last = newNode;
count++;
}
else
{
last.next = newNode;
newNode.back = last;
}
last = newNode;
}
public LinkedListNode partition(LinkedList list,
LinkedListNode first, LinkedListNode last)
{
LinkedListNode smallIndex = first;
LinkedListNode index = smallIndex.next;
LinkedListNode temp = new LinkedListNode();
int pivot = first.info;
while (index != last.next)
{
if((index.info) < pivot)
{
smallIndex = smallIndex.next;
temp.info = index.info;
index.info = smallIndex.info;
smallIndex.info = temp.info;
}
index = index.next;
}
temp.info = first.info;
first.info = smallIndex.info;
smallIndex.info = temp.info;
System.out.print("The list after QuickSort is: ");
list.print();
System.out.print("\n");
return smallIndex;
}
public void recQuickSort(LinkedList list, LinkedListNode first,
LinkedListNode last)
{
while(first != last)
{
LinkedListNode pivotLocation = partition(list, first, last);
recQuickSort(list, first, pivotLocation.back);
recQuickSort(list, pivotLocation.next, last);
}
}
public void quickSortLinkedList(LinkedList list)
{
recQuickSort(list, list.first, list.last);
}
}
import java.util.*;
public class testLinkedListQuickSort
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
LinkedList linkedlist = new LinkedList();
int num;
System.out.println("Enter numbers to add to linked list:");
num = console.nextInt();
while (num != 0)
{
linkedlist.insertNode(num);
num = console.nextInt();
}
linkedlist.quickSortLinkedList(linkedlist);
linkedlist.print();
}
}
Regarding your comments: you call partition with
recQuickSort(list, first, pivotLocation.back);
Do if pivotLocation.back is null then the partition method is called with last == null which leads to your NPE.
In your partition() method, you're not doing much checking for null values. For instance, if smallIndex, index, temp, or last are null, then that will blow up. There's also first, which if it's null, would cause the NPE.
It's a good idea to ensure that what you're being passed in the recursive call isn't an empty node. I don't see many checks for that.
NullPointerException occurs when you are trying to access a reference where there is no value.
Or when calling the instance method of a null object and accessing or modifying the field of a null object.
Or when you pass null to a method which expects a real value. It means to say that null object is used illegally.
I didnt looked at your code much but to resolve this, determine which Object instance is null and causing the problem. You will need to modify your code in order to add proper null check validations

Adding Polynomials (Linked Lists)......Bug Help

I have written a program that creates nodes that in this class are parts of polynomials and then the two polynomials get added together to become one polynomial (list of nodes). All my code compiles so the only problem I am having is that the nodes are not inserting into the polynomial via the insert method I have in polynomial.java and when running the program it does create nodes and displays them in the 2x^2 format but when it comes to add the polynomials together it displays o as the polynomials, so if anyone can figure out whats wrong and what I can do to fix it it would be much appreciated.
Here is the code:
import java.util.Scanner;
class Polynomial{
public termNode head;
public Polynomial()
{
head = null;
}
public boolean isEmpty()
{
return (head == null);
}
public void display()
{
if (head == null)
System.out.print("0");
else
for(termNode cur = head; cur != null; cur = cur.getNext())
{
System.out.println(cur);
}
}
public void insert(termNode newNode)
{
termNode prev = null;
termNode cur = head;
while (cur!=null && (newNode.compareTo(cur)<0))
{
prev = null;
cur = cur.getNext();
}
if (prev == null)
{
newNode.setNext(head);
head = newNode;
}
else
{
newNode.setNext(cur);
prev.setNext(newNode);
}
}
public void readPolynomial(Scanner kb)
{
boolean done = false;
double coefficient;
int exponent;
termNode term;
head = null; //UNLINK ANY PREVIOUS POLYNOMIAL
System.out.println("Enter 0 and 0 to end.");
System.out.print("coefficient: ");
coefficient = kb.nextDouble();
System.out.println(coefficient);
System.out.print("exponent: ");
exponent = kb.nextInt();
System.out.println(exponent);
done = (coefficient == 0 && exponent == 0);
while(!done)
{
Polynomial poly = new Polynomial();
term = new termNode(coefficient,exponent);
System.out.println(term);
poly.insert(term);
System.out.println("Enter 0 and 0 to end.");
System.out.print("coefficient: ");
coefficient = kb.nextDouble();
System.out.println(coefficient);
System.out.print("exponent: ");
exponent = kb.nextInt();
System.out.println(exponent);
done = (coefficient==0 && exponent==0);
}
}
public static Polynomial add(Polynomial p, Polynomial q)
{
Polynomial r = new Polynomial();
double coefficient;
int exponent;
termNode first = p.head;
termNode second = q.head;
termNode sum = r.head;
termNode term;
while (first != null && second != null)
{
if (first.getExp() == second.getExp())
{
if (first.getCoeff() != 0 && second.getCoeff() != 0);
{
double addCoeff = first.getCoeff() + second.getCoeff();
term = new termNode(addCoeff,first.getExp());
sum.setNext(term);
first.getNext();
second.getNext();
}
}
else if (first.getExp() < second.getExp())
{
sum.setNext(second);
term = new termNode(second.getCoeff(),second.getExp());
sum.setNext(term);
second.getNext();
}
else
{
sum.setNext(first);
term = new termNode(first.getNext());
sum.setNext(term);
first.getNext();
}
}
while (first != null)
{
sum.setNext(first);
}
while (second != null)
{
sum.setNext(second);
}
return r;
}
}
Here is my Node class:
class termNode implements Comparable
{
private int exp;
private double coeff;
private termNode next;
public termNode(double coefficient, int exponent)
{
coeff = coefficient;
exp = exponent;
next = null;
}
public termNode(termNode inTermNode)
{
coeff = inTermNode.coeff;
exp = inTermNode.exp;
}
public void setData(double coefficient, int exponent)
{
coefficient = coeff;
exponent = exp;
}
public double getCoeff()
{
return coeff;
}
public int getExp()
{
return exp;
}
public void setNext(termNode link)
{
next = link;
}
public termNode getNext()
{
return next;
}
public String toString()
{
if (exp == 0)
{
return(coeff + " ");
}
else if (exp == 1)
{
return(coeff + "x");
}
else
{
return(coeff + "x^" + exp);
}
}
public int compareTo(Object other)
{
if(exp ==((termNode) other).exp)
return 0;
else if(exp < ((termNode) other).exp)
return -1;
else
return 1;
}
}
And here is my Test class to run the program.
import java.util.Scanner;
class PolyTest{
public static void main(String [] args)
{
Scanner kb = new Scanner(System.in);
Polynomial r;
Polynomial p = new Polynomial();
System.out.println("Enter first polynomial.");
p.readPolynomial(kb);
Polynomial q = new Polynomial();
System.out.println();
System.out.println("Enter second polynomial.");
q.readPolynomial(kb);
r = Polynomial.add(p,q);
System.out.println();
System.out.print("The sum of ");
p.display();
System.out.print(" and ");
q.display();
System.out.print(" is ");
r.display();
}
}
A few suggestions:
Class names by convention starts with uppercase, e.g. TermNode
Use generics, i.e. TermNode implements Comparable<TermNode>
In fact, it's probably even better to have Node<Term> instead
Bugs I saw:
prev = null; in insert
Should be prev = cur;
Consider factoring this out to a helper find-like method
In readPolynomial, you're creating a new Polynomial every iteration, and doesn't do anything to this.
You want to either insert terms into this, or keep one Polynomial that you return at the end of a static readPolynomial method
while (first != null) sum.setNext(first);
What are you trying to accomplish here? This is an infinite loop!
More suggestions:
It may be easier/more readable/etc to do add in two passes:
merge polynomials first, making sure terms are properly ordered
3x+1 and 2x+2 merges to 3x+2x+1+2
Then simplify by merging any consecutive pairs of terms that have the same exponent
3x+2x simplifies to 5x
Once you get it working, consider optimizing it to add in one pass if necessary
In fact, the polynomial merging can be done easily in O(N^2) using insert
Get it correct first, optimize to O(N) later
While debugging/developing, print out the polynomials often. Do it after you read it. Do it after insertion. Do it after the first pass of add. Do it after the second pass.
One bug I can see right away is: while traversing the list you need to save the current node cur to prev before you move on so. But you are assigning null to prev all the time:
while (cur!=null && (newNode.compareTo(cur)<0)) {
prev = null;// <---- should be prev = cur;
cur = cur.getNext();

Categories

Resources