2014-05-20 224 views
-1

我對Java非常陌生,並且在我的二叉樹中搜索某個人時遇到了問題。我想要它,以便輸入什麼號碼將帶出該人(用戶名,姓名等)。從用戶輸入中搜索用戶

到目前爲止,這是我所:

BinaryTree Tree = new BinaryTree(); 
BinaryNode NodeAt; 

int TypeIn; 
Scanner user_input = new Scanner(System.in); 

Person PersonA = new Person(1,"PersonFirstName","PersonLastName","PersonPassword"); 
//Above repeated but PersonA becomes PersonB etc. 

Tree.Insert(PersonA); 
//Above repeated but PersonA becomes PersonB etc. 

Tree.InOrder(MyTree.gRoot()); 

TypeIn = user_input.nextInt() 

if (TypeIn == 1) { 
    NodeAt = MyTree.Find(PersonA); 
    System.out.println("NodeAt.gKey()); 
} 
// Repeat for other people (1 becomes 2, PersonA becomes Person B etc.) 

也有鏈接到這個Person類。

我大多很好奇,如果有一個更容易或更合適的方式來顯示用戶。我並不想複製if語句(if (TypeIn == 1))並將TypeIn更改爲2,3,4,5等等,PersonA更改爲PersonB。它確實是這樣工作的,只是想嘗試更整潔並學習其他方法。

+0

請嘗試使用標準的Java命名約定。這意味着用於變量和方法的camelcase以及用於類名(例如'int typeIn;','BinaryTree tree = new BinaryTree();','tree.insert(personA);'等)的上層庫。 – brimborium

回答

0

我會實現這樣的二叉樹類中的方法:

/** 
* 
* Search and returns the first node in the tree whose id match the passed id 
* 
* @param id of the searched person 
* 
* @return Person the found person 
*    or the special value Person#UNKOWN_PERSON if no matching id found 
*/ 
public Person findById(int id) { 
    // ... 


} 

在你的主代碼,你會:

Person p = MyTree.findById(user_input.nextInt()); 

這裏是UNKNOWN_PERSON的定義:

public class Person { 
    public static final Person UNKNOWN_PERSON = new Person(...); 

    // ... 
}