I have a code which works, but I need a main method.
can anyone please tel me where I can put the main method, I'm still struggling with that
and maybe someone can give me pointers for the future.
Thanks

public class BinaryTree {

BinaryTree left;
BinaryTree right;
int value;

public BinaryTree(int v) {
value = v;

}

// Insert a value into the tree
public void insert(int v) {

BinaryTree b = new BinaryTree(50);

b.insert(20);
b.insert(40);
b.insert(10);
b.insert(5);
b.insert(45);

b.insert(70);
b.insert(60);
b.insert(80);
b.insert(55);
b.insert(85);
b.preorder();

if(v < value) {
if(left == null)
left = new BinaryTree(v);
else
left.insert(v);
}

else if(v > value) {
if(right == null)
right = new BinaryTree(v);
else
right.insert(v);
}
}

public void preorder() {
System.out.println(value);
if(left != null) left.preorder();
if(right != null) right.preorder();


}
}

Recommended Answers

All 2 Replies

I don't know what you mean by "works" if you can't test it, but anyway...
The normal way to use main in a single class situation like yours goes like this:

public class XXX {
   XXX() { // constructor(s)
   ...
   // lots of method definitions
   ...
   public static void main(String[] args) {
      XXX x = new XXX();
      // call lots of methods on x with test data
      // print lots of results from x
   }
}

basically your lines 15-28 need to be in the main method.

Thanks! that helped me a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.