Java compare char on string array
Imagine I have a String array like this:
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"};
开发者_如何学JAVA
If I do this:
for (int i = 0; i < fruits.length;i++){
System.out.println(fruits[i][0].charAt(1));
}
it will print:
r
p
r
And if I do this:
for (int i = 0; i < fruits.length;i++){
Character compare = fruits[i][0].charAt(1);
System.out.println(compare.equals('r'));
}
it will print:
true
false
true
So here is my question. Is it possible to use charAt and equals on the same line, I mean, something like this:
System.out.println((fruits[i][0].charAt(1)).equals("r"));
Regards,
favolas
Yes, provided you convert the result of charAt()
to Character
first:
System.out.println(Character.valueOf(fruits[i][0].charAt(1)).equals('r'));
A simpler version is to write
System.out.println(fruits[i][0].charAt(1) == 'r');
I personally would always prefer the latter to the former.
The reason your version doesn't work is that charAt()
returns char
(as opposed to Character
), and char
, being a primitive type, has no equals()
method.
Another error in your code is the use of double quotes in equals("r")
. Sadly, this one would compile and could lead to a painful debugging session. With the char
-based version above this would be caught at compile time.
Certainly! Try this:
System.out.println((fruits[i][0].charAt(1)) == 'r');
We're doing a primitive comparison (char to char) so we can use == instead of .equals(). Note that this is case sensitive.
Another option would be to explicitly cast the char to a String before using .equals()
If you're using a modern version of Java, you could also use the enhanced for syntax for cleaner code, like so:
public static void main(String[] args) {
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"}};
for (String[] fruit: fruits){
System.out.println((fruit[0].charAt(1)) == 'r');
}
}
The char
data type, which is returned from String.charAt()
is a primitive, not an object. So you can just use the ==
operator to perform the comparison as it will compare the value, not the reference.
System.out.println((fruits[i][0].charAt(1) == 'r'));
精彩评论