比较两个字符串并读取一个数字

时间:2013-01-03 14:33:34

标签: java string equals

我让用户输入一个字符串(命令)。 我的代码是检查用户输入的内容。 例如“ADD”“DIVIDE”“SUBTRACT”等......

并且会像这样附上一个数字。 “ADD3”或“ADD5”

我应该如何以有效的方式对此进行编码, 而不是疯狂的if语句数量

这就是我现在所拥有的

public class Cell {

public static void main (String[] args) {

    String command = "";

    command= JOptionPane.showInputDialog(null, "Enter The Command" );

    if (command.equalsIgnoreCase("ADD")) {
              BLAH BLAH BLAH
}

2 个答案:

答案 0 :(得分:3)

我认为你应该这样做:

userInput.toLowerCase().startsWith("add"); // or divide/subtract/multiply...

我认为这段代码非常自我解释,除了toLowerCase()或许。这是为了模拟不区分大小写。

答案 1 :(得分:2)

最有效的方法是遵循 假设用户输入ADD 3

String[] inputs=command.split(" ");
String actualCommand=inputs[0];
int number=Integer.parseInt(inputs[1])

在此之后使用switchif-else检查实际命令并使用数字进行处理。

相关问题