javastringcharat

Java - confirming a match at a specific index in a string


Problem: Confirm if a specific character is at a specific index point of a string. For example, 'Hello' - is character H at index 0. I have managed to get this to work (as shown below). My issue is trying to add logical operators 'or' - || to allow for multiple options.

For example, at index 0, the letter could be H or M

The below works for confirming 'H' is at index '0'

if (myword.charAt(0)==('H')){
    System.out.println("True");
}    
else {
    System.out.println("False");
}

HOWEVER

if I then try to add a logical operator, this doesn't work and I just can't work out how to add logical operators to these type of scenarios.

if (myword.charAt(0)==('H')||('M')){
    System.out.println("True");
}    
else {
    System.out.println("False");
}

Solution

  • if (myword.charAt(0)=='H' || myword.charAt(0)== 'M'){
      System.out.println("True");
    } else {
      System.out.println("False");
    }
    

    Or

    System.out.println(
      myword.charAt(0)=='H' || myword.charAt(0)== 'M'
    );