繁体   English   中英

Java从字符串输入获取int

[英]Java get int from string input

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

您要测试哪棵树(BST,ST,RBT)?

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

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

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

我遇到的麻烦是第四选择。 例如,如果用户以字符串形式输入insert 100,那么我只需要摘下100并将其设为int。 如果是这样,我将如何去做?

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

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

如果此函数返回true ...字符串是整数...现在使用

Integer.parseInt(str);

我要注意的第一件事是,不应将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 */
    }
}

您还可以为每个愿意接受为有效选项的String可能性分配整数值。 这将增加编码,但也会增加switch case语句。 (它仍然被解释为,如果,否则,则为其他语句)我认为在那时,这将完全取决于开发人员的意图和设计偏好。 如果我错了,请纠正我。

您也可以使用try and catch块替换最终的else语句。

尝试这个:

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM