6

Is there any other way to shorten this condition?

if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") ||
oper.equals("Addition") || oper.equals("+"))

I was just wondering if there's something I can do to 'shortcut' this. The user will type a string when prompted what kind of operation is to be performed in my simple calculator program. Our professor said our program should accept whether the user enters "add", or "Add", you know, in lowercase letters or not... Or is the only way I should do it?

4

5 回答 5

9

您可以使用String#equalsIgnoreCase(String)第一个四个字符串:-

if (oper.equalsIgnoreCase("add") || 
    oper.equalsIgnoreCase("addition") || 
    oper.equals("+"))

如果字符串数量增加,最好使用 a List,并使用它的contains方法。但仅针对这些输入,您只能采用这种方法。


解决此问题的另一种方法是使用String#matches(String)方法,它采用正则表达式:-

if (oper.matches("add|addition|[+]")

但是,您实际上并不需要正则表达式。特别是,对于更大的输入,这种方法会变得很难看。但是,这只是这种情况的一种方式。因此,您可以选择其中任何一个。第一个在第一次观看时更清晰。


或者,您也可以使用enumto 存储operators,并将其实例传递到任何地方,而不是string. 使用起来会更容易。枚举看起来像这样:

public enum Operator {
    ADD,
    SUB,
    MUL,
    DIV;
}

您可以根据自己的需要对其进行增强。请注意,由于您正在获取用户输入,因此您首先需要根据它识别适当的枚举实例,然后您可以处理该枚举实例,而不是字符串。

于 2013-01-24T12:58:58.723 回答
4

除了@Rohit 的回答,我想补充一下。

在比较字符串的情况下,如果可以抛出oper is nulla 。NullPointerException所以写起来总是更好

"addition".equalsIgnoreCase(oper)

代替

oper.equalsIgnoreCase("addition")
于 2013-01-24T13:04:57.917 回答
3

如果aDD被认为是无效输入,则可以考虑以下方法:

ArrayList<String> possibleInputs = new ArrayList<String>();

possibleInputs.add("Add");
possibleInputs.add("add");
possibleInputs.add("Addition");
possibleInputs.add("addition");
possibleInputs.add("+");

if(possibleInputs.contains(oper))
{
    // ...
}
于 2013-01-24T13:03:30.500 回答
0

您可以获取输入,并将其转换为小写,然后进行比较。

str.toLowerCase()

然后传递给你的 if() 语句

if(str.equals("add") || str.equals("addition") || str.equals("+"))
于 2013-01-24T13:19:59.643 回答
0

将整段代码扔到一个名为: 的函数中,该函数isOperationAddition(String s){...}返回一个布尔值。

所以这:

if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") ||
    oper.equals("Addition") || oper.equals("+")){...}

对此的更改

if (isOperationAddition(operation)){...}

然后在该方法中,不要将字符串用作 if 语句的分支材料。有一个变量来定义它是哪种操作,并“让野蛮人(困惑/模棱两可的用户)远离护城河”。您不应该总是对列表进行迭代以记住我们正在处理的操作。

于 2013-01-24T13:03:18.483 回答