Ask Question
18 June, 13:53

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.

+2
Answers (1)
  1. 18 June, 15:12
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers