Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the first 2 letters in a sting are a specific value

Tags:

java

Edit Thanks for the help guys got it working now.

So I had a question to do to ask a user for first name and last name which I have done no problem but then I thought it's be good to expand the program so that if someone entered a surname like McCabe it would print T McC instead of TM. I'm just not sure about how to compare the first two letters of the secondname string to see if they are "mc".

public class InitialsAlt {

  public static void main(String [] args){

    Scanner keyboardIn = new Scanner (System.in);
    String firstname = new String();
    System.out.print (" Enter your first name ");
    firstname = keyboardIn.nextLine();
    String secondname = new String();
    System.out.print (" Enter your second name ");
    secondname = keyboardIn.nextLine();

   if(secondname.charAt(0, 1)== "mc" ) {
      System.out.print("Your initals are " + firstname.charAt(0)+    secondname.charAt(0,1,2)); 
   }

   else {
   System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0));
   }

  }
}
like image 643
Ant695 Avatar asked Dec 06 '25 00:12

Ant695


1 Answers

if (secondName.toLowerCase().startsWith("mc")) {
like image 99
Reimeus Avatar answered Dec 07 '25 16:12

Reimeus