Trying to create a BST that sorts Fractions. The treenode class
public class TreeNode<E> {
protected E element;
protected TreeNode<E> left;
protected TreeNode<E> right;
public TreeNode(E e){
element = e;
}
}
The fractions class...
import java.util.ArrayList;
import java.util.Stack;
public class Fractions {
private String fractionS;
private ArrayList<String> tokenArray;
public Fractions(String s){
this.fractionS = s;
}
public String toString(){
return fractionS;
}
public String extractNumber(int n, String s){
String num = new String ();
char c;
for (int i = n; i<s.length(); i++){
c = s.charAt(i);
if (c >= '0' && c <= '9'){
num+=String.valueOf(c);
}else{
break;
}
}
return num;
}
public Double getNumbers(){
char c;
Stack<String> numStack = new Stack<String>();
for (int i = 0; i<this.fractionS.length(); i++){
c = this.fractionS.charAt(i);
if (c >= '0' && c<= '9'){
numStack.push(extractNumber(i, this.fractionS));
i += numStack.peek().length()-1;
}
}
Double denominator = Double.parseDouble(numStack.pop());
Double numerator = Double.parseDouble(numStack.pop());
Double solution = numerator/denominator;
return solution;
}
public int compareTo(Fractions f) {
Double d1 = this.getNumbers();
Double d2 = f.getNumbers();
if (d1<=d2){
return 1;
}else{
return 0;
}
}
I get a NullPointerException
on the call for compareTo
method. Just trying to figure out the NullPointerException
. I can do the rest myself. This is for a class, and I don't want to get in trouble.
Including the instantiating of fractions... I also made changes to fractions class.
public void createTree(){
tokenizer();
Stack<String> numbers = new Stack<String>();
int count = 0;
for (int i = 0; i<tokenArray.size(); i++){
char c = tokenArray.get(i).charAt(0);
if (c == '/'){
count+= 1;
}else if (c >= '0' && c <= '9'){
numbers.push(tokenArray.get(i));
}
}
for (int i = 0; i <count; i++){
String denominator = numbers.pop();
String numerator = numbers.pop();
insert(new Fractions(numerator + "/" + denominator));
}