gpt4 book ai didi

java - BinaryTree - 带开关盒

转载 作者:行者123 更新时间:2023-12-04 05:12:05 25 4
gpt4 key购买 nike

我玩了一点二叉树并构建了一个菜单,当我单击创建树时,用户可以选择是构建二叉树、向他构建的二叉树插入值还是删除它。树被创建,然后菜单再次出现,现在我想在这棵树中放一个数字,但是在案例中没有设置该变量,每个案例都应该设置它的变量?或者你可以使用全局变量?
这是我的菜单类代码。

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);

}
}

}

}

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

最佳答案

声明 tree1作为私有(private)全局变量

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

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

需要注意的是,您需要在 case 2 and 3 中进行错误检查。 , 如果 tree1 == null ,这意味着尚未创建任何树。

关于java - BinaryTree - 带开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14789593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com