我要注意的第一件事是,不应将 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 语句。