Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading