1

I have a program that allows the user to choose between a binary search tree a splay tree and a red black tree. I wrote the class for the binary search tree and now im working on the splay tree but ive realized that my method that interacts with the user only works with the binary search tree. I set it up so that it will create an instance of whichever tree the user selects but down in my code I use only the variable that would be created if the user selected a binary search tree. My question is how can i make it so that I will only create an instance of the tree that the user selected and how can i use only one variable so that when i insert items or work on the tree i dont have to add more conditional statements for different trees?

this is what i have now

import java.util.Scanner;
import java.lang.Math.*;
public class Driver1
{ 


public static void main(String[] args)
{
    //local variables
    String treeChoice = null;
    String choice = null;
    String choice2 = null;
    String command = null;
    int insertAmount = -1;
    String pattern;
    int height = -1;
    int i = -1;
    //BST<Integer> myTree = null;
    //ST<Integer> mySTTree = null;

    int num = 0;


    //Scanners to take user input
    Scanner input = new Scanner(System.in);
    Scanner inputt = new Scanner(System.in);
    System.out.println("Which tree would you like to test (BST, ST, RBT)? ");
    treeChoice = input.nextLine();

    //Based on user input either a BST, Splay Tree, or RBT will be initialized.
    if("BST".equalsIgnoreCase(treeChoice))
    {
        BST<Integer> myTree = new BST<Integer>();
    }
    else if("ST".equalsIgnoreCase(treeChoice))
    {
        //System.out.println("Splay Tree not ready yet");
        ST<Integer> mySTTree = new ST<Integer>();
    }
    else if("RBT".equalsIgnoreCase(treeChoice))
    {
        System.out.println("RBT not ready yet");
        //RBT<Integer> myTree = new RBT<Integer>();
    }
    else
    {
        System.out.println("Invalid Entry");
    }

    //Ask user how many items to input
    System.out.println("How many items would you like to insert? ");
    insertAmount = input.nextInt();

    //ask user if the items will be random or sorted
    System.out.println("Pattern (random or sorted): ");
    choice2 = inputt.nextLine();

    //If random, create random numbers
    if("random".equalsIgnoreCase(choice2))
    {
        for(i = 1; i <= insertAmount; i++)
        {
            myTree.insert((int)(Math.random()*1000000)+i);
        }
    }
    //else fill the tree with numbers in order from 1 to the user limit
    else if("sorted".equalsIgnoreCase(choice2))
    {
        for(i = 1; i <= insertAmount; i++)
        {
            myTree.insert(i);
        }
    }
    //Keep asking users input on what to do to the tree until user says quit
    while(command != "quit")
    {
        System.out.println(
        "Next command (insert X, delete X, find X, height, quit)?");
        command = inputt.nextLine();


        if (command.startsWith("insert")) 
        {
         num = Integer.parseInt(command.replaceAll("\\D", ""));
         boolean result = myTree.insert(num);
         if(result == false)
         {
            System.out.println("Item already present.");
         }

        }
         else if(command.startsWith("delete"))
         {
            num = Integer.parseInt(command.replaceAll("\\D", ""));
            boolean result = myTree.delete(num);
        }
        else if(command.startsWith("find"))
        {
            num = Integer.parseInt(command.replaceAll("\\D", ""));
            boolean result = myTree.find(num);
            if(result == true)
            {
                System.out.println("Item present.");
            }
            else
            {
                System.out.println("Item not present.");
            }

        }
        else if(command.startsWith("height"))
        {
            System.out.println("Current height of tree " + myTree.height());
        }
        else if(command.startsWith("quit"))
        {
            break;
        }
        System.out.println();
    }   
}//Close main method

as you can see I fill only myTree which would be the tree created if the user selected bst. and in the while loop i only work on myTree.

How can i make this more generic or my other idea was to take the users input and then create the instance of that tree and then pass the instance into a seperate method so that i could still use only myTree since it would refer to the instance that was passed into that method but im not sure how to pass an instance into another method. This way seems like the best but im not sure

any help is appreciated

user214577
  • 363
  • 1
  • 7
  • 15

1 Answers1

1

Your trees should extend a common base class, or better, a implement common interface, say Tree, that specifies the methods to be used on all trees (find, insert, delete). Then you should have only one variable Tree myTree to which you assign an actual instance of the type the user selects.

Are you sure your above code works, however? If you do this

if("BST".equalsIgnoreCase(treeChoice))
{
    BST<Integer> myTree = new BST<Integer>();
}

then the variable myTree will be unavailable after the } because the code block in which it is declared ends there. You can declare a variable at one point and assign a value to it later, like so:

Tree<Integer> myTree;
if("BST".equalsIgnoreCase(treeChoice)) {
    myTree = new BinarySearchTree<Integer>();
} else if("ST".equalsIgnoreCase(treeChoice)) {
    myTree = new SplayTree<Integer>();
} else if("RBT".equalsIgnoreCase(treeChoice)) {
    myTree = new RedBlackTree<Integer>();
} else {
    throw new IllegalArgumentException(treeChoice + " is not a valid input");
}

I very much recommend that you give your classes real names that make obvious what they represent, not just two or three letter combinations. Note that if you do not throw an exception in the last else branch, the compiler will later complain that "the variable myTree may not have been initialized".

Alternatively, you could put all your code after the tree creation if-else-statements into a method, say <T> void testTree(Tree<T> myTree) and call this method directly where you evaluate the user input, e.g. if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>());, but at some you will want to assign it to a variable anyway.

arne.b
  • 4,212
  • 2
  • 25
  • 44
  • in the line Tree what would Tree be? – user214577 Mar 07 '13 at 08:05
  • @user214577 The interface that defines the methods your tree classes have in common (as mentioned in the first sentence). See, for example, [what is an interface](http://docs.oracle.com/javase/tutorial/java/concepts/interface.html). – arne.b Mar 07 '13 at 08:09