[英]Comparing Two String List Elements
I'm working on a game in Java and I need to compare the first character an element in a list with another character of an element in a separate list, as an if statement. 我正在使用Java进行游戏,我需要将列表中的第一个字符与单独列表中元素的另一个字符进行比较,作为if语句。 What would be the best way to do that? 最好的方法是什么?
So far I have: 到目前为止,我有:
if((user.get(0)).equals(pack.get(0)))
I'm just not sure how to at the .charAt() to this. 我只是不确定如何在.charAt()这个。
List<String> list1 = new ArrayList<String>();
list1.add("ant");
List<String> list2 = new ArrayList<String>();
list2.add("apple");
list2.add("bear");
//comparing 'a' from "ant" from list1 with 'a' from "apple" from list2
System.out.println(list1.get(0).charAt(0) == list2.get(0).charAt(0)); //true
//comparing 'a' from "ant" from list1 with 'b' from "bear" from list2
System.out.println(list1.get(0).charAt(0) == list2.get(1).charAt(0)); //false
Assuming you need to compare every element in the list with all others you could try this: 假设您需要将列表中的每个元素与其他元素进行比较,您可以尝试这样做:
List<String> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++) {
for(int j = i + 1; j < list.size(); j++) {
if(list.get(i).charAt(0) == list.get(j).charAt(0)) {
//code executed if true
}
}
}
if ( string1.charAt(0) == string2.charAt(0) ){
//Your code to handle the equality here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.