How i can do search() with stack - java

I'm trying to figure out how i can show all numbers in the stack i have, to do search method without using library. For example
if(value = allNumbers){
return true;
}
else{
return false;
}
The problem is I can't find the correct method how to display allNumbers in the stack
My code:
public class Stack <T>{
private Item<T> q=null;
public boolean isEmpty() {
return q==null;
}
public void push(T d) {
Item<T> tmp=new Item<T>(d);
tmp.next=q;
q=tmp;
}
public T pop() {
if (isEmpty())
return null;
T tmp=q.data;
q=q.next;
return tmp;
}
public T peek(){
if (isEmpty())
return null;
T tmp = q.data;
return tmp;
}
// public boolean search (T value) {
// if(value == null ) {
// return false;
// }
// else{
// value = allNumbers ;
// return true;
// }
//
// }
}
Driver code:
public class Driver {
public static void main(String[] args) {
Stack<Integer> s=new Stack<Integer>();
int value = 2;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.push(7);
s.push(8);
s.push(9);
System.out.println("Popped: " + s.pop());
System.out.println("Last number put in is: " + s.peek());
// System.out.println("Searching for: " );
// System.out.println("Is found: " + s.search(9));
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
}

I would assume your 'Item' class is custom since you haven't added any imports. The solution with that in mind is to add a method that takes in one parameter (data) and traverses all the items in the "q" list. If an item matches the data, return true. If not, return false. Also, remember to implement the 'equals()' method appropriately in the 'Item' class.
The implementation of the search method should be pretty much this:
public boolean search(T value) {
if (value == null) {
return false;
}
Item<T> item = q;
while (q != null) {
if (q.equals(value))
return true;
}
return false;
}

Related

turning pointer to LinkedList of ArrayList into String

I'm trying to make a linkedList (elements) of custom arrayList (coordinated )that with type Object
the Output I am looking for is
Arraylist1 coord1 [2,5,1]
Arraylist2 coord2 [7,6,9]
LinkedList List1 [[2,5,1],[7,6,9]]
this is my output
[ 2 5 1 ]
[ 7 6 9 ]
assignment1.arrayList#33909752
assignment1.arrayList#55f96302
I tried using toString method with no luck
can someone please explain to me how to print the output with no pointers to memory.
and do I need a method to access a specific element in a certain position (in the linkList) and get its coordinates?
here is my code:
thanks
public class arrayList {
private Object[] myList;
private int counter = 0;
private int capacity = 100;
public arrayList() {
myList = new Object[this.capacity];
}
public Object get(int index) {
if (index < counter) {
return myList[index];
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(Object obj) {
myList[counter++] = obj;
}
public Object remove(int index) {
if (index < counter) {
Object obj = myList[index];
int temp = index;
myList[index] = null;
while (temp < counter) {
myList[temp] = myList[temp + 1];
myList[temp + 1] = null;
temp++;
}
counter--;
return obj;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public int size() {
return counter;
}
public void display(Object obj1) {
System.out.print("[");
for (int i = 0; i < this.size(); i++) {
System.out.print(" " + this.get(i) + " ");
}
System.out.print("]");
System.out.println();
}
}
public class linkedList {
public Cube firstLink;
public Cube next;
linkedList() {
firstLink = null;
}
public void insertFirstLink(Object e) {
Cube newLink = new Cube(e);
newLink.next = firstLink;
firstLink = newLink;
}
public boolean isEmpty() {
return (firstLink == null);
}
public Cube removeFirst() {
Cube linkReference = firstLink;
if (!isEmpty()) {
firstLink = firstLink.next;
} else {
System.out.println("Empty Linked list!");
}
return linkReference;
}
public void display() {
Cube theLink = firstLink;
while (theLink != null) {
theLink.display();
theLink = theLink.next;
System.out.println();
}
}
public Cube find(Object obj) {
Cube theLink = firstLink;
if (!isEmpty()) {
while (theLink.obj != obj) {
if (theLink.next == null) {
return null;
} else {
theLink = theLink.next;
}
}
} else {
System.out.println("Empty List!");
}
return theLink;
}
public Cube removeLink(Object obj) {
Cube currentLink = firstLink;
Cube previousLink = firstLink;
while (currentLink.obj != obj) {
if (currentLink.next == null) {
return null;
} else {
previousLink = currentLink;
currentLink = currentLink.next;
}
}
if (currentLink == firstLink) {
firstLink = firstLink.next;
} else {
previousLink.next = currentLink.next;
}
return currentLink;
}
}
public class Cube {
public Object obj;
public Cube next;
public Cube(Object obj) {
this.obj = obj;
}
public void display() {
obj.toString();
System.out.println(obj);
}
public static void main(String[] args) {
arrayList coord1 = new arrayList();
coord1.add(new Integer(2));
coord1.add(new Integer(5));
coord1.add(new Integer(1));
arrayList coord2 = new arrayList();
coord2.add(new Integer(7));
coord2.add(new Integer(6));
coord2.add(new Integer(9));
coord1.display(coord1);
coord2.display(coord2);
linkedList position1 = new linkedList();
position1.insertFirstLink(coord1);
position1.insertFirstLink(coord2);
position1.display();
}
}
According to the API, https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(java.lang.Object)
You put a Object into System.out.println(x) will eventually call String.valueOf(x) which utlimitly call x.toString(). Put this #1
In linkedList.display() it will call Cube.display(). Cube.display() will prints its encapsulated object. The object turns out to be an arrayList. From #1, the method call would become arrayList.toString(). However, arrayList did not implement toString(). Don't worry, Java got your back. Since all non-primitive type extends Object, arrayList will has is toString() method inherited from Object. This is the Object implementation, to print the object id. If you don't like it, you can define your own toString() in arrayList scope.
Update 1
You may wonder why the first arraylist could print something meaningful out. It is because you call its arraylist.display() directly, not System.out.println(coord1)
Update 2
There are some anti pattern in your code.
Class name should be in camel case
, like Cube so as ArrayList, LinkedList.
Why arrayList.display() need a argument which also reference to itself but you never use it (i.e. obj1 is totally ignored)?
coord1.display() is good enough, you don't need coord1.display(coord1)
You need to do following changes:
In your arrayList class you need to change methods display(Object obj1) and override toString() method:
public void display(Object obj1) {
System.out.println(obj1);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < counter - 1; i++) {
sb.append(myList[i] + ",");
}
sb.append(myList[counter - 1] + "]");
return sb.toString();
}
In class linkedList change display and override toString() as below:
public void display() {
System.out.println(this.toString());
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
Cube temp = firstLink;
sb.append("[");
while (temp != null) {
sb.append(temp.obj.toString());
temp = temp.next;
if (temp != null)
sb.append(",");
}
sb.append("]");
return sb.toString();
}
}
Note: It will be printing linked list in reverse order, because your implementation of LinkedList is storing data in reverse order.

Properly Writing Object Oriented Code in java for a stack

I'm trying to write code in a way that it is object oriented. In this particular case I want to keep track of the minimum value of my stack in O(1) time. I know how to do it, the idea of it, well my idea of it, which is to have another stack that keeps track of the minimum value for every push and pop.
I've nested every class inside of the program class which is called minStack, which doesn't seem like the right thing to do however when I create a instance of minStack and call its variables it works out fine for a regular stack. I created a class that extends a Stack called StackWithMin but I don't know how to call its values. Should I create a new instance of a StackWithMin? If so how would i do it? I did it at the end of the code above the main function, but peek() always returns null
class minStack {
public class Stack {
Node top;
Object min = null;
Object pop() {
if(top != null) {
Object item = top.getData();
top = top.getNext();
return item;
}
return null;
}
void push(Object item) {
if(min == null) {
min = item;
}
if((int)item < (int)min) {
min = item;
}
Node pushed = new Node(item, top);
top = pushed;
}
Object peek() {
if(top == null) {
//System.out.println("Its null or stack is empty");
return null;
}
return top.getData();
}
Object minimumValue() {
if(min == null) {
return null;
}
return (int)min;
}
}
public class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setData(Object d) {
data = d;
}
public Object getData() {
return data;
}
}
public class StackWithMin extends Stack {
Stack s2;
public StackWithMin() {
s2 = new Stack();
}
public void push(Object value) {
if((int)value <= (int)min()) {
s2.push(value);
}
super.push(value);
}
public Object pop() {
Object value = super.pop();
if((int)value == (int)min()) {
s2.pop();
}
return value;
}
public Object min() {
if(s2.top == null) {
return null;
}
else {
return s2.peek();
}
}
}
Stack testStack = new Stack();
StackWithMin stackMin = new StackWithMin();
public static void main(String[] args) {
minStack mStack = new minStack();
//StackWithMin stackMin = new StackWithMin();
mStack.testStack.push(3);
mStack.testStack.push(5);
mStack.testStack.push(2);
mStack.stackMin.push(2);
mStack.stackMin.push(4);
mStack.stackMin.push(1);
System.out.println(mStack.testStack.peek());
System.out.println(mStack.stackMin.peek());
mStack.testStack.pop();
}
}
I would suggest to create generic interface Stack like this one
interface Stack<T> {
void push(T item);
T pop();
T peek();
}
Generics add stability to your code by making more of your bugs
detectable at compile time.
See more about generics here.
Then implement this interface in a common way. All implementation details will be hidden inside of this class (your Node class for example). Here is the code (it is just to show the idea, if you want to use it you need to improve it with exception handling for example). Note that class Node is now also generic.
class SimpleStack<T> implements Stack<T> {
private class Node<T> { ... }
private Node<T> root = null;
public void push(T item) {
if (root == null) {
root = new Node<T>(item);
} else {
Node<T> node = new Node<T>(item, root);
root = node;
}
}
public T pop() {
if (root != null) {
T data = root.getData();
root = root.getNext();
return data;
} else {
return null;
}
}
public T peek() {
if (root != null) {
return root.getData();
} else {
return null;
}
}
}
Now we get to the part with stored minimum value. We can extend our SimpleStack class and add field with another SimpleStack. However I think this is better to make another implementation of the Stack and store two stacks for values and for minimums. The example is below. I have generalize the class that now uses Comparator to compare object, so you can use any other object types.
class StackWithComparator<T> implements Stack<T> {
private Comparator<T> comparator;
private SimpleStack<T> mins = new SimpleStack<>();
private SimpleStack<T> data = new SimpleStack<>();
public StackWithComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
public void push(T item) {
data.push(item);
if (mins.peek() == null || comparator.compare(mins.peek(), item) >= 0) {
mins.push(item);
} else {
mins.push(mins.peek());
}
}
public T pop() {
mins.pop();
return data.pop();
}
public T peek() {
return data.peek();
}
public T min() {
return mins.peek();
}
}
Now you can use both implementations like so
SimpleStack<Integer> s1 = new SimpleStack<>();
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop()); // print 3
System.out.println(s1.pop()); // print 2
System.out.println(s1.pop()); // print 1
StackWithComparator<Integer> s2 = new StackWithComparator<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
});
s2.push(1);
s2.push(2);
s2.push(3);
s2.push(0);
s2.push(4);
System.out.println(s2.min() + " " + s2.pop()); // print 0 4
System.out.println(s2.min() + " " + s2.pop()); // print 0 0
System.out.println(s2.min() + " " + s2.pop()); // print 1 3
System.out.println(s2.min() + " " + s2.pop()); // print 1 2
System.out.println(s2.min() + " " + s2.pop()); // print 1 1

Implementing own hashset

I was studying about hashset in java and for that I am writing creating my own hashset which will double its size everytimme the threshold value is reached..here I am keeping the threshold as 0.75 of original size . However my code is running into an infinite loop. I tried debugging it but was not able to find my error...
here is the code
package drafta;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HashSet
{
private Node[] buckets;
private int currentSize;
private int current;
public HashSet(int bucketsLength)
{
buckets=new Node[bucketsLength];
currentSize=0;
}
public boolean contains(Object x)
{
return false;
// don't implement for the draft
}
public boolean add(Object x)
{
int key=gethashcode(x);
Node node = buckets[key];
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
if(buckets[current]==null){
node = new Node(x);
current=key;
buckets[key]=node;
currentSize++;
}else{
node = new Node(x);
node.next=buckets[current];
current=key;
buckets[key]=node;
currentSize++;
}
System.out.println("add successful "+ x);
System.out.println(" size "+currentSize+" rehash "+buckets.length*0.75);
if(currentSize>(buckets.length*0.75)){
rehash();
}
return true;
}
private void rehash() {
Node temp=buckets[current];
Object s[]=new Object[buckets.length];
buckets=new Node[2*buckets.length];
currentSize=0;
int i=0;
while(temp!=null){
s[i]=temp.data;
temp=temp.next;
i++;
}
while(i>0){
add(s[--i]);
}
}
public boolean remove(Object x)
{
return false;
// don't implement for draft
}
public int gethashcode(Object x){
int hc = x.hashCode();
if(hc<0)
hc=-hc;
return (hc%buckets.length);
}
public Iterator<Object> iterator()
{
Iterator <Object> i=new HashSetIterator();
return i;
//
}
public int size()
{
return currentSize;
//
}
private void resize(int newLength)
{
}
public int getlength()
{
return buckets.length;
//
}
class Node
{
public Object data;
public Node next;
public Node(Object x) {
data=x;
}
public String toString(){
return data.toString();
}
}
class HashSetIterator implements Iterator<Object>
{
private int bucket=0;
private Node currentnode;
public HashSetIterator()
{
currentnode=buckets[current];
}
public boolean hasNext()
{
if(currentnode.next!=null)
return true;
else
return false;
//
}
public Object next()
{
return currentnode.next;
//
}
#Override
public void remove() {
currentnode.next=currentnode.next.next;
}
}
}
this is the main class which I am using to test my code
package drafta;
import java.util.Iterator;
public class HashSetTester
{
public static void main(String[] args)
{
HashSet names = new HashSet(5);
names.add("Harry");
names.add("Sue");
names.add("Nina");
System.out.println(names.size() + " " + names.getlength());
names.add("Susannah");
System.out.println(names.size() + " " + names.getlength());
System.out.println();
names.add("Larry");
names.add("Juliet");
names.add("Katherine");
names.add("Romeo");
names.add("Maria");
System.out.println(names.size() + " " + names.getlength());
names.add("Ann");
names.add("Taylor");
System.out.println(names.size() + " " + names.getlength());
}
}
can someone please point out my mistake..the code is going into infintie loop when it calls rehash for second time..first time it goes through correctly...
You arn't changing any conditions in your while loop in the add method - so there is no reason for it to break out.
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
You will continue looping until the node is null (which never gets set) or the node data ever equals x, but the data value also never gets set.

Inexplicable Issue with Add Method of a Simple Binary Tree

My binary tree looks pretty close to my class materials, but when I print to the console or check for contains(), any adds I'm doing aren't registered.
I don't have a great understanding of static and the debugger is giving me a hint about making a static reference to non-static variable overallRoot, but everything compiles without error or warning in eclipse.
public class BSTSimpleSet<E extends Comparable<E>> implements SimpleSet<E> {
private GTNode<E> overallRoot;
private int size;
public static void main(String[] args) {
BSTSimpleSet<Integer> main = new BSTSimpleSet<Integer>(2);
main.toString();
main.add(3);
main.toString();
main.add(4);
main.toString();
main.add(5);
main.toString();
System.out.print(main.contains(3));
}
public BSTSimpleSet() {
size = 0;
}
public BSTSimpleSet(E input) {
overallRoot = new GTNode<E>(input);
size = 1;
}
public boolean add(E e) {
return add(e, overallRoot);
}
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return false;
} else if (compare < 0) {
return add(e, root.left);
} else {
return add(e, root.right);
}
}
}
public void clear() {
overallRoot = null;
}
public boolean contains(E e) {
return contains(e, overallRoot);
}
private boolean contains(E e, GTNode<E> root) {
if (root == null) {
return false;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(e, root.left);
} else {
return contains(e, root.right);
}
}
}
public boolean isEmpty() {
if (overallRoot == null) {
return false;
} else {
return true;
}
}
public int size() {
return size;
}
public String toString() {
this.toString(overallRoot, 0);
return null;
}
private void toString(GTNode<E> root, int level) {
if (root != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.data);
toString(root.left, level + 1);
toString(root.right, level + 1);
} else {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("_");
}
}
private static class GTNode<E extends Comparable<E>> {
public E data;
public GTNode<E> left;
public GTNode<E> right;
public GTNode(E input) {
this(input, null, null);
}
public GTNode(E input, GTNode<E> lNode, GTNode<E> rNode) {
data = input;
left = lNode;
right = rNode;
}
}
}
This code does absolutely nothing.
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
}
...
Java passes in the Object Reference to a method. If you change the Reference, that will not
be propagated back to the calling method. If you change what the Reference refers to
that will be propagated back.
eg
// arrays behave the same way so using them to illustrate.
public void callMethods(){
int[] array = new int[1];
array[0] = 0;
doesNotChange(array);
System.out.println(array[0]);// will print 0
doesAChange(array);
System.out.println(array[0]);// will print 1
}
public void doesNotChange(int[] myArray){
myArray = new int[1];
myArray[0] = 1;
}
public void doesAChange(int[] myArray){
myArray[0] = 1;
}
To avoid these sorts of things I recommend always setting method parameters final.
The GTNode class shouldn't be static. Static classes are classes with only static methods, which means they don't have to be instantiated. The prototypical example of this is the java.lang.Math class: You don't need to call something like Math m = new Math(); m.cos(); to get the cosine, you just call Math.cos(). Since you're creating multiple instances of the GTNode class, make it non-static and you should be good.

When reading from a Scanner in a loop, it goes into an infinite loop [duplicate]

This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 3 years ago.
Two problems here. When I try to traverse this home-grown binary tree using a "recursive iterator" (an iterator that traverses the tree recursively, puts the elements into a queue, and then removes the elements from the front of the queue). The iterator tends to iterate backwards (greatest to least) instead of inorder (least to greatest). Also, when I try to read user input from a Scanner using nextInt(), the program goes into an infinite loop. I'm trying to catch the InputMismatchException when the user inputs an invalid number.
In the below code segment, I'm catching the InputMismatchException when the user doesn't input a number so that the program continues normally.
Testing file:
package assignments.unit9;
import java.util.*;
import static java.lang.System.*;
import java.io.*;
public class BinaryTreeTest
{
private static BinaryTree<Item> tree;
static Scanner user;
public static void main(String... args)
{
user = new Scanner(System.in);
int choice;
do
{
out.println("1. Read data from disk");
out.println("2. Print the tree in order");
out.println("3. Search the tree");
out.println("4. Delete from the tree");
out.println("5. Count the nodes in the tree");
out.print("0. Quit\n>");
try
{
choice = user.nextInt();
}
catch(InputMismatchException e)
{
choice = -1;
}
switch(choice)
{
case 0:
exit(0);
case 1:
try
{
readFromDisk();
}
catch(FileNotFoundException e)
{
err.println("Sorry, but the file could not be opened: " + e.getMessage());
}
break;
case 2:
if(tree == null)
{
err.println("Must read file first");
break;
}
printTree();
break;
case 3:
if(tree == null)
{
err.println("Must read file first");
break;
}
searchTree();
break;
case 4:
if(tree == null)
{
err.println("Must read file first");
break;
}
// deleteFromTree();
break;
case 5:
if(tree == null)
{
err.println("Must read file first");
break;
}
countNodes();
break;
default:
err.println("Invalid choice. The available choices are:");
break;
}
}
while(choice != 0);
}
public static void readFromDisk() throws FileNotFoundException
{
Scanner file = new Scanner(new File("file20.txt"));
tree = new BinaryTree<Item>();
if(file.hasNextInt())
file.nextInt(); //skip the first integer
while(file.hasNextInt())
{
tree.add(new Item(file.nextInt(), file.nextInt()));
}
}
public static void printTree()
{
tree.inorder();
}
public static void searchTree()
{
out.println("Enter ID value to search for (-1 to return)");
int search;
Item searched;
while((search = user.nextInt()) != -1)
{
out.println(searched = tree.find(new Item(search, 0)));
if(searched == null)
out.println("\b\b\b\b\bNo such part in stock");
}
}
public static void countNodes()
{
out.println(tree.countNodes());
}
}
Here, in the BinaryTree class, I try to traverse it recursively (see iterator() and asQueue()):
package assignments.unit9;
import java.util.*;
public class BinaryTree<E extends Comparable<E>> implements Iterable<E>
{
private TreeNode<E> root;
public void add(E value)
{
if(root == null)
{
root = new TreeNode<E>(value);
}
else
{
TreeNode<E> temp = root, upFrom = null;
boolean goesOnLeft = false;
while(true)
{
if(temp == null)
{
if(goesOnLeft)
upFrom.setLeft(new TreeNode<E>(value));
else
upFrom.setRight(new TreeNode<E>(value));
break;
}
else if(temp.getValue().compareTo(value) < 0) //goes on left
{
upFrom = temp;
temp = upFrom.getLeft();
goesOnLeft = true;
continue;
}
else //goes on right
{
upFrom = temp;
temp = upFrom.getRight();
goesOnLeft = false;
continue;
}
}
}
}
public void inorder()
{
try
{
inorder(root);
}
catch(StackOverflowError e)
{
System.err.println("Increase stack size to print remaining elements");
}
}
private void inorder(TreeNode<E> t)
{
if(t == null)
return;
inorder(t.getLeft());
System.out.println(t.getValue());
inorder(t.getRight());
}
private ArrayDeque<E> asQueue(TreeNode<E> t, ArrayDeque<E> toAdd)
{
try
{
if(toAdd == null)
toAdd = new ArrayDeque<E>();
if(t == null)
return toAdd;
asQueue(t.getLeft(), toAdd);
toAdd.addLast(t.getValue());
asQueue(t.getRight(), toAdd);
ret:
return toAdd;
}
catch(StackOverflowError e)
{
throw new InternalError();
}
}
public Iterator<E> iterator()
{
return new Iterator<E>()
{
private ArrayDeque<E> d = asQueue(root, null);
public E next()
{
return d.pop();
}
public boolean hasNext()
{
return !d.isEmpty();
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
public int countNodes()
{
int toReturn = 0;
for(E elem : this)
++toReturn;
return toReturn;
}
public E find(E toFind)
{
for(E elem : this)
{
if(elem.equals(toFind))
return elem;
}
return null;
}
}
TreeNode class:
package assignments.unit9;
import java.util.Objects;
public class TreeNode<T>
{
private T value;
private TreeNode<T> left, right;
/**
* Constructs a new TreeNode value with the left and right pointers {#code null}.
*
* #param value the item to be referenced
*
* #throws NullPointerException if {#code value} is {#code null}.
*/
public TreeNode(T value)
{
this.value = Objects.requireNonNull(value);
}
/**
* Constructs a new TreeNode value with the specified left and right pointers.
*
* #param value the item to be referenced
* #param left the TreeNode value to the left.
* #param right the TreeNode value to the right.
*
* #throws NullPointerException if {#code value} is {#code null}.
*/
public TreeNode(T value, TreeNode<T> left, TreeNode<T> right)
{
this.value = Objects.requireNonNull(value);
this.left = left;
this.right = right;
}
public T getValue()
{
return value;
}
public TreeNode<T> getLeft()
{
return left;
}
public TreeNode<T> getRight()
{
return right;
}
public void setValue(T value)
{
this.value = Objects.requireNonNull(value);
}
public void setLeft(TreeNode<T> left)
{
this.left = left;
}
public void setRight(TreeNode<T> right)
{
this.right = right;
}
}
Data type (Item):
package assignments.unit9;
import java.util.*;
public class Item implements Comparable<Item>
{
private int myID;
private int myInv;
//Comparators
public static class IDComparator implements Comparator<Item>
{
public int compare(Item i1, Item i2)
{
return i1.getID() - i2.getID();
}
#Override
public boolean equals(Object obj)
{
return obj instanceof IDComparator;
}
}
public static class InvComparator implements Comparator<Item>
{
public int compare(Item i1, Item i2)
{
return i1.getInv() - i2.getInv();
}
#Override
public boolean equals(Object obj)
{
return obj instanceof InvComparator;
}
}
public Item(int id, int inv)
{
myID = id;
myInv = inv;
}
public int getID()
{
return myID;
}
public int getInv()
{
return myInv;
}
public int compareTo(Item i)
{
if(i == null)
throw new NullPointerException();
return this.myID - i.myID;
}
#Override
public boolean equals(Object otherObject)
{
Item i;
try
{
i = (Item) otherObject;
return myID == i.myID;
}
catch(ClassCastException ex)
{
return false;
}
}
public String toString()
{
return "ID: " + myID + "\tInventory number: " + myInv + "\n";
}
#Override
public int hashCode()
{
return Objects.hash(myID, myInv);
}
}
And here's the input file. Sorry if that's a lot:
20
196 60
18618 64
2370 65
18410 56
18465 27
19967 45
17911 96
184 14
18871 69
14088 92
18061 3
206 31
13066 8
12705 14
15917 51
15814 60
15320 82
8303 90
7282 73
12328 63
Your printout function prints the nodes in reverse order because that's the way you're storing them; your binary tree has the larger value on the left, instead of the right, because you have a ">" instead of a "<" in your 'add' function. Change that and they come out increasing instead of decreasing.
I still don't see the conditions under which you get an endless loop, and I don't get one myself. Put the program into a debugger and track where it's going until you figure it out. I honestly think I've done enough on this question (I don't have Java 7 and had to backfill it to Java 6 to run it), and I'm moving on.
Okay, problem solved. The thing is, I had typed a < when I needed a > and so I was ending up with the larger values on the left and the smaller values on the right, so my inorder traversal was backwards. Second, the infinite loop caused by catching InputMismatchException was a bug in the Scanner class:
The program starts, starting the loop which calls in.nextInt() in
the try block.
When the user inputs a non-number, the Scanner
throws an InputMismatchException, which diverts flow to the
catch block, which sets choice to -1 which causes the invalid
text block to be shown.
But what's weird is that in the next
iteration, when nextInt() is called, it immediately throws an
exception instead of getting input, which can be seen if a print
statement is added to the catch block.
Thanks everyone who helped me on this.

Categories