149k views
4 votes
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.

User Xomby
by
4.3k points

1 Answer

4 votes

Answer:

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;

}

}

}

Step-by-step 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
User Jacob Zwiers
by
3.2k points