I played a bit with binary trees and built a menu which the user chooses whether to build a binary tree, insert a value to the binary tree he built or delete it, when I clicked on the creation of a tree. The tree is created, then the menu appeared again and now I want to put a number in this tree, but that variable is not set in the case, each case should set its variable ? Or you can use a global variable?
here its my code of the menu class.
import java.util.Comparator;
import java.util.Scanner;
public class TreeMenu {
public static void main(String[] args) {
while(true ){
System.out.println("\n------------Menu-----------");
System.out.println("1. Create Tree");
System.out.println("2. Delete Tree");
System.out.println("3. Insert Value INTO the tree");
System.out.println("4. Exit ");
System.out.println("Please Select Your Choice");
Scanner choice = new Scanner(System.in);
int i = choice.nextInt();
if(i>0 && i<=4){
switch (i)
{
case 1:{
System.out.println("Creating a Tree Please Wait........");
Comparator comp = new IntegerComparator();
BST tree1 = new BST(comp);
break;
}
case 2:{
System.out.println("You Chose TWO");
break;
}
case 3:{
Scanner Number = new Scanner(System.in);
int num = Number.nextInt();
tree1.insert(num);
}
case 4:{
System.exit(0);
}
}
}
else{
System.out.println("There is no number in the menu like that "+i);
System.exit(0);
}
}
}
}
how i can use the same tree that created and insert into him values?
thanks
Declare
tree1as a private global variable asNow instantiate that
tree1inside theswitch case 1, then you can use the same tree variable insidecase 2A thing to note is you would need to do error checking in
case 2 and 3, iftree1 == null, that would mean no tree has been created yet.