如何在Java中找到ArrayList中元素的位置?

Mai*_*jat 2 java arraylist

我的代码将用户输入的字符与具有字符的 ArrayList 进行匹配,并显示结果。我使用循环和 IF 语句来打印匹配字符和不匹配字符的不同结果。我使用 Array.Contains() 方法将用户输入与 ArrayList 元素进行比较。我试图在匹配时打印元素在 ArrayList 中的位置。

例如:ArrayList 有:[a, b, c, d] 和位置(a 为 0,b 为 1,c 为 2,d 为 3)。如何以编程方式打印匹配元素的位置?

这是我的代码:

ArrayList<Character> charsList = new ArrayList<Character>();

for (int i = 0; i < wordsList[0].length(); i++) {
    charsList.add(wordsList[0].charAt(i));
}

for (int i = 0; i < wordsList[0].length(); i++) {
    inputValue = input.next().charAt(0);
    if (charsList.contains(inputValue)) {
        System.out.println("Matched!");  
    }
    else {
        System.out.println("Not Matched!");
    }   
}
Run Code Online (Sandbox Code Playgroud)

erg*_*aut 5

您可以使用 indexOf 方法。

System.out.println(charList.indexOf(inputValue));
Run Code Online (Sandbox Code Playgroud)