0

我正在写一个二叉搜索树。用户将按如下方式使用该程序:

您想测试哪棵树(BST、ST、RBT)?

BST 您要插入多少个项目?10000 模式(随机或排序)?排序下一个命令(插入 X、删除 X、查找 X、高度、退出)?查找 111111 项目不存在。

对于前三个选择,我认为我可以只使用字符串在 BST、ST 和 RBT 之间进行选择,也可以在随机或排序之间进行选择,比如

String choice
if( choice == "random")
  insert random numbers

我遇到的问题是第四个选择。例如,如果用户将插入 100 作为字符串输入,我是否只需要去掉 100 并将其设为 int。如果是这样,我将如何去做?

4

3 回答 3

4

您可以使用函数的组合来确定字符串是否为 int

public boolean isInteger(String str) {
  try {
    Integer.parseInt(str);
    return true;
  } catch(NumberFormatException e) {
    return false;
  }
}

如果此函数返回 true ... string 是一个整数 ...现在使用获取整数值

Integer.parseInt(str);
于 2013-03-01T04:20:04.483 回答
1

我要注意的第一件事是,不应将 String 与 == 进行比较,而应使用 string.equals(comparedString); 您还可以使用以下代码解析一个人输入的所有输入,然后同时使用输入的字符串和输入的字符串值,它不会依赖于字符串的开头。这将满足他们所有人的选择;插入、删除等。

String userInput;//received by system in
String choice;
int choiceInt;
for (int i = 0; i < userInput.length(); i++) 
{
    Character character = userInput.charAt(i);
    if (!Character.isDigit(character)) 
    {
        choice += character;
    }
    else if (Character.isDigit(character))
    {
        choiceInt += character;
    }
    else
    {
        System.out.println("Unable to determine character.");
    }

    /* Code for the comparison of String based option */
    //Example
    if (choice.equalsIgnoreCase("insert")//NOTE: the ignore case, 
                                         // you want users to be                        
                                         // able to enter in strings 
                                         // and not have a case sensitivity.
    {
        /* do the code you planned on doing here */
    }
}

您还可以为您愿意接受为有效选项的每个字符串可能性分配整数值。这将增加编码,但也会增加 switch case 语句。(这仍然被解释为 if、else if、else 语句)我认为在这一点上这将更多地取决于开发人员的意图和设计偏好。如果我错了,请纠正我。

您还可以使用 try 和 catch 块替换最后的 else 语句。

于 2013-07-16T18:12:32.370 回答
0

尝试这个:

if (input.startsWith("insert")) {
    int num = Integer.parseInt(input.replaceAll("\\D", ""));

}
于 2013-03-01T05:00:34.543 回答