1

ユーザーがバイナリ検索ツリー、スプレイツリー、赤黒ツリーのいずれかを選択できるようにするプログラムがあります。私はバイナリ サーチ ツリーのクラスを作成し、現在はスプレイ ツリーに取り組んでいますが、ユーザーと対話する私のメソッドはバイナリ サーチ ツリーでのみ機能することに気付きました。ユーザーが選択したツリーのインスタンスを作成するように設定しましたが、コードでは、ユーザーが二分探索ツリーを選択した場合に作成される変数のみを使用します。私の質問は、ユーザーが選択したツリーのインスタンスのみを作成するようにするにはどうすればよいか、また、アイテムを挿入したりツリーで作業したりするときに条件ステートメントを追加する必要がないように、変数を 1 つだけ使用するにはどうすればよいかということです。別の木のため?

これは私が今持っているものです

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

ご覧のとおり、ユーザーが bst を選択した場合に作成されるツリーである myTree のみを入力します。while ループでは、myTree でのみ作業します。

これをより一般的にするにはどうすればよいですか、または私の他のアイデアは、ユーザー入力を取得してそのツリーのインスタンスを作成し、インスタンスを別のメソッドに渡して、インスタンスを参照するため myTree のみを使用できるようにすることでしたそのメソッドに渡されましたが、インスタンスを別のメソッドに渡す方法がわかりません。この方法が最善のようですが、よくわかりません

どんな助けでも大歓迎です

4

1 に答える 1

1

ツリーは、すべてのツリー ( 、、 )Treeで使用されるメソッドを指定する、共通の基本クラスを拡張するか、共通のインターフェイスを実装する必要があります。次に、ユーザーが選択した型の実際のインスタンスを割り当てる変数を 1 つだけ持つ必要があります。findinsertdeleteTree myTree

ただし、上記のコードが機能することは確かですか? こうすれば

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

変数が宣言されているコードブロックがそこで終了myTreeするため、変数は使用できなくなります。}次のように、ある時点で変数を宣言し、後でそれに値を割り当てることができます。

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");
}

2、3 文字の組み合わせだけでなく、クラスが何を表しているのかが明確になるような実際の名前をクラスに付けることを強くお勧めします。最後の分岐で例外をスローしない場合else、コンパイラは後で「変数 myTree が初期化されていない可能性がある」と文句を言うことに注意してください。

または、ツリー作成の if-else-statements の後にすべてのコードをメソッドに入れることもでき<T> void testTree(Tree<T> myTree)ます。たとえば、ユーザー入力を評価する場所でこのメソッドを直接呼び出すことができますif("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>());

于 2013-03-07T07:55:57.117 に答える