0

事情就是这样。我有一个字符数组如下..

char[] modes = new char[] { 'm', 'q', 'h', 'y' };

现在我想为用户提供输入字符的选项。如果它存在于modes数组中,我会做必要的。为此,我使用...

//to take a character as input
mode = input.next().charAt(0);
//now to check if the array contains the character
boolean ifExists = Arrays.asList(modes).contains(mode);

却诡异ifExists归来false

  1. 任何想法我在哪里做错了?
  2. 如果这是一种不好的方法,请提出一种方法。
4

5 回答 5

3

我认为这是自动装箱 - contains() 方法采用对象,而不是原语。

如果您使用 Character 而不是 char 它将起作用:

    Character[] modes = new Character[] { 'm', 'q', 'h', 'y' };

    //to take a character as input
    Character mode = "q123".charAt(0);
    //now to check if the array contains the character
    boolean ifExists = Arrays.asList(modes).contains(mode);

返回真

于 2013-01-23T16:37:06.997 回答
3

Arrays.asList() 方法返回一个 char[] 列表,而不是您期望的 char 列表。我建议使用 Arrays.binarySort() 方法,如下所示:

    char[] modes = new char[] { 'm', 'q', 'h', 'y' };

    char mode = 'q';

    //now to check if the array contains the character
    int index = Arrays.binarySearch(modes, mode);
    boolean ifExists = index != -1;
    System.out.print(ifExists);
于 2013-01-23T16:40:30.723 回答
1

我没有发现你的代码有任何问题,试试这个,

如果您使用这种Colletions,那么您可以使用默认可用的方法进行大量操作......

List<Character> l = new ArrayList<Character>();
l.add('a');
l.add('b');
l.add('c');
System.out.println(l.contains('a'));
于 2013-01-23T16:41:19.100 回答
1

您可以只转换为字符串,然后运行包含

new String(modes).contains("" + mode);

然后,这应该为您的原始数组返回 true 或 false

于 2013-01-23T16:43:54.673 回答
0

您还可以使用字符串 indexOf:

boolean ifExists = new String(modes).indexOf(mode) >= 0;

或者

boolean ifExists = "mqhy".indexOf(mode) >= 0;
于 2018-12-03T12:19:02.823 回答