Java 将对象传递给方法

标签 java binary-search-tree splay-tree

我有一个程序,允许用户在二叉搜索树、伸展树(Splay Tree)和红黑树之间进行选择。我为二叉搜索树编写了类,现在我正在研究伸展树(Splay Tree),但我意识到我与用户交互的方法仅适用于二叉搜索树。我对其进行了设置,以便它将创建用户选择的树的实例,但在我的代码中,我仅使用用户选择二叉搜索树时将创建的变量。我的问题是我怎样才能做到这一点,以便我只创建用户选择的树的实例,以及如何仅使用一个变量,以便当我插入项目或在树上工作时,我不必为不同的树添加更多条件语句?

这就是我现在拥有的

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

正如你所看到的,我只填充了 myTree,如果用户选择 bst,这将是创建的树。在 while 循环中我只在 myTree 上工作。

我怎样才能使这个更通用,或者我的另一个想法是获取用户输入,然后创建该树的实例,然后将该实例传递到一个单独的方法中,以便我仍然只能使用 myTree,因为它会引用传递到该方法中的实例,但我不确定如何将实例传递到另一个方法中。这种方式似乎是最好的,但我不确定

感谢任何帮助

最佳答案

你的树应该扩展一个公共(public)基类,或者更好的是,一个实现公共(public)接口(interface),比如 Tree ,指定要在所有树上使用的方法( findinsertdelete )。那么你应该只有一个变量 Tree 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");
}

我强烈建议您为类(class)提供真实姓名,以明确其代表的含义,而不仅仅是两个或三个字母的组合。注意如果最后没有抛出异常else分支,编译器稍后会提示“变量 myTree 可能尚未初始化”。

或者,您可以将树创建后的所有代码 if-else-语句放入一个方法中,例如 <T> void testTree(Tree<T> myTree)并在评估用户输入时直接调用此方法,例如if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>()); ,但在某些情况下你还是想将它分配给一个变量。

关于Java 将对象传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15265779/

相关文章:

language-agnostic - 伸展树(Splay Tree)插入

java - 为什么@Deprecated注解使用RetentionPolicy.RUNTIME?

java - JSTL if-then-else session 属性

c - BST崩溃程序添加Node功能

algorithm - 具有键值的Haskell二叉树

c++ - 查找 'SEGV on unknown address' 的原因,由 READ 访问引起

java - 如何使用 iBatis

java - 使用仅适用于第一次测试的流进行单元测试日志

Java实现BST删除节点