簡體   English   中英

Java將對象傳遞給方法

[英]Java Pass object to method

我有一個程序,允許用戶在二進制搜索樹,展開樹和紅色黑樹之間進行選擇。 我為二進制搜索樹編寫了類,現在我在splay樹上工作,但我意識到與用戶交互的方法僅適用於二進制搜索樹。 我對其進行了設置,以便它將創建用戶選擇的任何樹的實例,但是在我的代碼中,我僅使用如果用戶選擇了二進制搜索樹將創建的變量。 我的問題是我該怎么做,以便僅創建用戶選擇的樹的實例,如何只使用一個變量,這樣當我插入項目或在樹上工作時,我不必添加更多條件語句不同的樹木?

這就是我現在所擁有的

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,因為它將引用該實例。被傳遞給該方法,但是我不確定如何將實例傳遞給另一個方法。 這種方式似乎是最好的,但我不確定

任何幫助表示贊賞

您的樹應擴展一個公共基類,或者更好的擴展為一個實現公共接口,例如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");
}

我非常建議您為您的班級提供真實的名稱,使它們的含義顯而易見,而不僅僅是兩個或三個字母組合。 請注意,如果未在最后一個else分支中引發異常,則編譯器稍后將抱怨“變量myTree可能尚未初始化”。

或者,您可以將創建樹后的if-else語句后的所有代碼放入方法中,例如<T> void testTree(Tree<T> myTree)並在您評估用戶輸入的位置直接調用此方法,例如if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>()); ,但無論如何,您還是希望將其分配給變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM