Manivel Sundaresan
Manivel Sundaresan

Reputation: 157

Comparing two characters in java

   import java.util.Scanner;

    public class Main {
    private static Scanner scan;
    private static int n;
    private static int b[];
    private static String a1;
    private static String a2;
    private static int t[];

    public static void main(String s[]) {
        scan = new Scanner(System.in);
        n = scan.nextInt();
        b = new int[n];
        t = new int[n];
        for (int i = 0; i < n; i++) {
            b[i] = scan.nextInt();
        }

        a1 = scan.next();
        a2 = scan.next();

        for (int i = 0; i < n; i++) {
            Character c = a1.charAt(i);
            Character c2 = a2.charAt(i);
            if (c.equals("G")) {
                if (c2.equals("G")) {
                    System.out.println(i);
                }
            }
        }
    }

}

I am getting n value (i.e.) number of bags. Then Apples in each Bag. For that, I am using for loop. Then two Strings. Strings should be of either 'G' or 'B', (e.g.) 'GGGBG' (G for Good and B for Bad).

Consider these two strings from different person's opinion about the apples in the bags. If both String contains 'G' in same position, then the code should display that position.

But, It is not working. I was trying to run this code. Input part is working. After that, it displays nothing in the screen.

Upvotes: 2

Views: 1038

Answers (1)

Andreas
Andreas

Reputation: 159086

charAt(i) returns a char, not Character, though the compiler will auto-box it into one.

However, Character is never equal to String.

Your code should be:

for (int i = 0; i < n; i++) {
    char c1 = a1.charAt(i);
    char c2 = a2.charAt(i);
    if (c1 == 'G' && c2 == 'G') {
        System.out.println(i);
    }
}

Upvotes: 6

Related Questions