0

How can I compare two characters in Java?

while(s1.hasNext()) {
    if(a[j].equals('x')
        x++;
    if(a[j].equals('y')
        y++;
}

I have repeated the loop using for loop for n times and a[j] is an array. I am getting the error at if condition inside the while loop. Could anyone please explain me about the error?

Pang
  • 9,564
  • 146
  • 81
  • 122
Chaitanya
  • 63
  • 1
  • 2
  • 10

1 Answers1

0

you can also compare characters using == as following:

while(s1.hasNext())
{
    if(a[j] == 'x')
    x++;
    if(a[j]=='y')
    y++;
}

here array a should be a character array.

If a is a string than you have to use s.charAt(int index) to get desired character, as following:

while(s1.hasNext())
{
    if(a.charAt(j) == 'x')
    x++;
    if(a.charAt(j) == 'y')
    y++;
} 
Kaushal28
  • 5,377
  • 5
  • 41
  • 72