2013-02-09 42 views
2


我玩了一点二叉树,并建立了一个菜单,用户选择是否构建二叉树,插入一个值到他建立的二叉树或删除它,当我点击创建一棵树。树被创建,然后菜单又出现了,现在我想在这棵树上放一个数字,但是这个变量没有在这个case中设置,每个case都应该设置它的变量?或者你可以使用全局变量?
这里是我的菜单类的代码。
BinaryTree - 带开关盒

import java.util.Comparator; 
import java.util.Scanner; 


public class TreeMenu { 

public static void main(String[] args) { 

    while(true){ 
     System.out.println("\n------------Menu-----------"); 
     System.out.println("1. Create Tree"); 
     System.out.println("2. Delete Tree"); 
     System.out.println("3. Insert Value INTO the tree"); 
     System.out.println("4. Exit "); 
     System.out.println("Please Select Your Choice"); 

     Scanner choice = new Scanner(System.in); 
     int i = choice.nextInt(); 
     if(i>0 && i<=4){ 
     switch (i) 
      { 

      case 1:{ 

       System.out.println("Creating a Tree Please Wait........"); 
       Comparator comp = new IntegerComparator(); 
       BST tree1 = new BST(comp); 
       break; 
      } 
      case 2:{ 
       System.out.println("You Chose TWO"); 
       break; 
      } 
      case 3:{ 
       Scanner Number = new Scanner(System.in); 
       int num = Number.nextInt(); 
       tree1.insert(num); 

      } 
      case 4:{ 
       System.exit(0); 

      } 

      } 

      } 
     else{ 
      System.out.println("There is no number in the menu like that "+i); 
      System.exit(0); 

     } 
    } 

} 

} 

我如何使用创建并插入到他的值的同一棵树?
感谢

+0

在main while循环外面加上'BST tree1'变量。 – nhahtdh 2013-02-09 15:29:29

回答

3

声明tree1作为私有全局变量作为

public class TreeMenu { 
    private static BST tree1 = null; 
    ..... 

现在实例化tree1switch case 1里面,那么你可以使用相同的树变量中case 2

一个需要注意的一点是你需要在case 2 and 3中进行错误检查,如果是tree1 == null,那意味着还没有创建树。

+0

是的,我知道..谢谢! – 2013-02-09 15:35:12