0

My question is: is there any possibility of listing a set of values to search for in an if-statement? Or is there a better way of doing this? for example:

Scanner input=new Scanner (System.in);
String searchTerm=input.next();

if(input==1d,2d,3d,4d,5c,1a,3x,5c,6b){
    // Do stuff
}

EDIT: very sorry, I did not realise my question wasn't completed, and even kind of wrong... Gosh. Fixed now.

4

8 回答 8

4
if (!Arrays.asList(1d,2d,3d,4d,5c,1a,3x,5c,6b).contains(input)) {
    // do stuff
}
于 2013-11-06T16:59:34.843 回答
2

我建议使用一个列表:

  • 将要搜索的值添加到列表中。
  • 如果输入是值之一,请使用List.contains(Object o) (文档)检查。
于 2013-11-06T17:00:09.673 回答
1

您可以从值创建一个列表,然后检查包含

if (list.contains(input))
于 2013-11-06T16:58:35.367 回答
1

将它们转换为ListusingArrays.asList和 use contains

if (!Arrays.asList("1d", "2d", "3d", "4d", "5c", "1a", "3x", "5c", "6b").contains(input)) {
    // Do stuff
}
于 2013-11-06T16:59:03.780 回答
1

创建一个新集合并查看是否在其中找到值:

if(!(Arrays.AsList("1d", "2d", "3d", "4d").Contains(input))){ }
于 2013-11-06T16:59:17.433 回答
1

将一组值放入集合中。例如:

Set<String> invalidInputs = new HashSet<String>();
validInputs.add("1d"); //and all the rest

然后检查该集合是否包含输入:

if(!invalidInputs.contains(input) {
    //do stuff
}
于 2013-11-06T16:59:33.577 回答
1

您需要使用 if 语句进行单独比较(这没有使用 Java 更高级的东西)。如果您要比较多个值,我建议您使用 Switch 语句。

switch (input){
    case '1d': case '2d': case '3d': case '4d': case '5c': case '1a': case '3x': case '6b':
        //do something
        break;
    default:
        //do something
}
于 2013-11-06T17:00:47.007 回答
1

尝试使用数组。

String[] test= {"1d","2d","3d","4d","5c","1a","3x","5c","6b"};
        for(int i=0;i<test`length;i++)
            if(!input.contentEquals(test[i]))
            {
                //Something
            }
于 2013-11-06T17:06:42.660 回答