Ask Question
5 October, 06:52

Write a program named Lab7B that will read 2 strings and compare them. Create a bool function named compareLetters that will accept 2 string variables as parameters and will return true if the strings have the same first letters and the same last letters. It will return a false otherwise.

+5
Answers (1)
  1. 5 October, 10:16
    0
    import java. util.*;

    public class Lab7B {

    public static void main (String[] args) {

    Scanner in = new Scanner (System. in);

    System. out. println ("Enter first String");

    String word1 = in. next ();

    System. out. println ("Enter Second String");

    String word2 = in. next ();

    System. out. println (compareLetters (word1, word2));

    }

    public static boolean compareLetters (String wrd1, String wrd2) {

    int len1 = wrd1. length ();

    int len2 = wrd2. length ();

    if (wrd1. charAt (0) = =wrd2. charAt (0) &&wrd1. charAt (len1-1) = =wrd2. charAt (len2-1)) {

    return true;

    }

    else{

    return false;

    }

    }

    }

    Explanation:

    Using Java Programming Language Import Scanner class to receive user input Prompt user for two string and save in variables Create the compareLetters method to accept two string parameters Using the charAt () function extract the first character (i. e charAt (0)). Extract also the last character (charAt (lengthOfString-1) Use if statement to compare the first and last characters and return true or false
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a program named Lab7B that will read 2 strings and compare them. Create a bool function named compareLetters that will accept 2 ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers