我有一個菜單驅動的程序,提示用戶輸入整數以創建BST。一切工作都很棒,但如果用戶返回到主菜單並選擇創建新的二叉搜索樹,則新輸入實際上只是添加到舊樹中。我知道這是因爲我在switch語句之外創建了我的樹,但是,如果我在第一個switch語句內部創建它,以便創建一棵新樹,其他switch語句將無法訪問該樹...關於我應該在哪裏創建我的樹的任何想法?將對象從開關盒中取出
package model;
import java.io.*;
import java.util.*;
public class menu {
public static void main(String[] args){
int integerInput;
int inputOption;
int myCategoryChoice;
InOrder inOrder;
PreOrder preOrder;
PostOrder postOrder;
Context context;
BinaryTree myIntTree;
myIntTree = new BinaryTree();
inOrder = new InOrder();
preOrder = new PreOrder();
postOrder = new PostOrder();
Scanner userInput = new Scanner(System.in);
do{
System.out.println("=======================================");
System.out.println(" Binary Search Tree Traversal! ");
System.out.println("=======================================");
System.out.println("Options: ");
System.out.println(" 1. Create a new binary search tree ");
System.out.println(" 2. Traverse the tree ");
System.out.println(" 3. Quit ");
System.out.println("=======================================");
inputOption = KeyIn.inInt("Please select an option from the menu: ");
switch(inputOption){
case 1:
System.out.println("You've selected to create a new binary tree." + "\n");
Scanner scan = new Scanner(System.in);
String tempInput;
Boolean repeat = true;
try{
System.out.println("Please enter as many integers as you'd like, hit 'Q' when you are finished." + "\n");
do{
tempInput = scan.next();
if(!tempInput.equals("Q") && !tempInput.equals("q")){
integerInput = Integer.parseInt(tempInput);
myIntTree.insert(integerInput);
repeat = true;
}
else
repeat = false;
}while(repeat);
}catch (NumberFormatException e) {
System.out.println("Invalid input. Not an integer");
}
break;
case 2:
System.out.println("Let's traverse the tree we just made!. ");
myCategoryChoice = KeyIn.inInt("Please select a traversal method: (1) Pre-Order (2) In-Order (3) Post-Order");
Boolean done = false;
do{
switch(myCategoryChoice){
case 1:
System.out.println("You've selected a pre-order traversal." + "\n");
context = new Context(preOrder);
context.traverse(myIntTree);
done = true;
break;
case 2:
System.out.println("You've selected an in-order traversal." + "\n");
context = new Context(inOrder);
context.traverse(myIntTree);
done = true;
break;
case 3:
System.out.println("You've selected a post-order traversal." + "\n");
context = new Context(postOrder);
context.traverse(myIntTree);
done = true;
break;
}
}while(!done);
break;
case 3:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid selection.");
break;
}
} while(inputOption != 3);
}
}
你正在使用什麼'BinaryTree'類? – 2012-08-06 00:19:00
我創建了一個..這會影響我將創建它的位置嗎? – 2012-08-06 00:24:38