java - 使用 split() 并检查第二个元素

标签 java split binary-search-tree user-input indexoutofboundsexception

我有一个二叉搜索树的代码,它将接受用户输入,例如 insert 3 它将调用 3 上的插入函数。当我尝试调用不需要参数的函数(例如我的遍历函数)时,除非用户输入是 traverse 0,否则它将给出越界错误。我想仅使用 traverse 来调用它,这是我的代码:

 public static void main(String[] args) 
{
    int quit = 0;
    BinarySearchTree bst = new BinarySearchTree();
    Scanner in = new Scanner(System.in);

    //Accept user input and call funtions
    while(quit != 1)
    {
        System.out.print("\nEnter the instructions to perform (type quit when done):");
        String input = in.nextLine();
        String[] instruction = input.split(" ");
        String function = instruction[0].toLowerCase();
        String parameter = instruction[1];
        //What to do with user input
        if(function.equals("insert"))// for insert
        {
            int key = Integer.parseInt(parameter);
            bst.insert(key);
            System.out.println(parameter + " was inserted successfully!");
        }
        else if(function.equals("delete"))// for delete
        {
            int key = Integer.parseInt(parameter);
            if(bst.delete(key) == true)
                System.out.println(parameter + " was deleted successfully!");
            else
                System.out.println(parameter + " does not exist.");
            bst.delete(key);
        }
        else if(function.equals("search"))// for search
        {
            int key = Integer.parseInt(parameter);
            if(bst.search(key) == true)
                System.out.println(parameter + " was found!");
            else
                System.out.println(parameter + " not found.");
            bst.search(key);
        }
        else if(function.equals("traverse"))// for traverse
        {
            bst.traverse(BinarySearchTree.root);
        }
    }

}//end main

最佳答案

当您尝试将指令[1]分配给参数时,就会出现问题。如果输入字符串中没有空格字符,则 split 方法将返回长度为 1 的数组,并且当您尝试访问第二个元素时,您将收到超出范围的异常。

解决办法是:

if (input.equals("traverse")) {
    ...
} else {
    String[] instructions = input.split(" ");
    assert instruction.length == 2;
    String function = instruction[0].toLowerCase();
    int key = Integer.parseInt(instruction[1]);
    ...
}

有更好的方法来建模命令。理想情况下,您会使用 command pattern而不是 if 语句。但如果您不想遇到这个麻烦,您至少应该考虑使用模式来使解析更加健壮。

Pattern commandPattern = Pattern.compile("(traverse|search|delete|insert) *(\\d*)");
Matcher matcher = commandPattern.match(in.nextLine());
if (!matcher.matches()) {
    System.out.println("Illegal command. Try again.");
    matcher = commandPattern.match(in.nextLine());
}
switch (matcher.group(1).toLowerCase()) {
    case "traverse":
        bst.traverse(root);
        break;
    case "delete":
        int deleteKey = Integer.parseInt(matcher.group(2));
        if (bst.delete(deleteKey)) {
            ...

关于java - 使用 split() 并检查第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400660/

相关文章:

split - Angular2 拆分字符串(管道?)

c - 了解从二叉搜索树中删除节点的递归调用

c++ - 为 C++ 二叉搜索树使用智能指针

python - 元组的二分查找

java - 在 Java 中创建 JDBC 连接池

java - 当另一个线程在创建 XML 文件时正在解析它时,解析 xml 文件时会出现文件过早结束异常

r - 将字符串拆分为多个固定宽度的列

javascript - 基于多个分隔符计算项目?

java - 如何使用osgi在CQ5中显示 "hello world"

java - 在 Redis 重启时自动将 Storm Topology 重新连接到 Redis Cluster