Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compare char on string array

Tags:

java

Imagine I have a String array like this:

String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"};

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

like image 404
Favolas Avatar asked Dec 21 '22 08:12

Favolas


2 Answers

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.

like image 196
NPE Avatar answered Jan 09 '23 00:01

NPE


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');
            }

}
like image 39
Chad Schultz Avatar answered Jan 08 '23 23:01

Chad Schultz