我有一个菜单驱动程序,提示用户输入整数以创建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);
}
}
答案 0 :(得分:1)
声明变量而不初始化它。然后,只要用户输入1
:
public static void main(String[] args){
//...
BinaryTree myIntTree = null;
inOrder = new InOrder();
preOrder = new PreOrder();
postOrder = new PostOrder();
//...
case 1:
myIntTree = new BinaryTree();
//...
case 2:
if(myIntTree == null) break;
//...
}
或者,由于您创建了自己的BinaryTree
类,因此可以创建clear()
方法从树中删除每个节点并调用它。