1
我的代码与由用户输入的具有字符的ArrayList匹配,并显示结果。我使用循环和IF语句为匹配的字符和不匹配的字符打印不同的结果。我使用Array.Contains()方法来比较用户输入与ArrayList元素。我试图在匹配时在ArrayList中打印元素的位置。例如:ArrayList具有:[a,b,c,d]和位置(a代表0,a代表1,b代表2,c代表2代表d,3代表d)。我怎样才能以编程方式打印匹配元素的位置?如何在Java中的ArrayList中查找元素的位置?
这里是我的代码:
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!");
}
}
要小心,这只返回第一次出现或-1如果不存在。如果您的列表包含重复项,您可以创建新的子列表或将第一次出现迭代到最后一个索引。 – Ghokun
看来,OP使用charList作为参考集,这听起来是一个独特的集合。 – ergonaut