Define a class to declare an array to accept and store ten words. Display only those words which begin with the letter 'A' or 'a' and also end with the letter 'A' or 'a'. EXAMPLE: Input : Hari, Anita, Akash, Amrita, Alina, Devi, Rishab, John, Farha, AMITHA Output: Anita Amrita Alina AMITHA
Topic: Filtering words by first and last letter
Answer
import java.util.Scanner;
class WordFilter { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String w[] = new String[10];
System.out.println("Enter 10 words :"); for(int i = 0; i < 10; i++) w[i] = sc.next();
System.out.println("Words beginning and ending with A or a :"); for(int i = 0; i < 10; i++) { char f = w[i].charAt(0); char l = w[i].charAt(w[i].length() - 1);
if((f == 'A' | | f == 'a') && (l == 'A' | | l == 'a'))
System.out.println(w[i]); } } }
Two skills combine here: getting the first and last characters of a string, and building a condition that mixes | | with &&.
The first character is charAt(0). The last is charAt(length() - 1) — the minus one is essential, since the last index is always one less than the length.
The condition needs care with brackets. Both the beginning AND the ending must match, but each may be either capital or small:
| (f == 'A' | f == 'a') && (l == 'A' | l == 'a') | ||
|---|---|---|---|---|
| Without the inner brackets, Java would apply && before | and the test would be wrong. When mixing the two operators, always bracket explicitly. |
A neater alternative worth mentioning: convert the word with toUpperCase() first, then test only against 'A' twice.
Trace the sample: Anita, Amrita, Alina and AMITHA all begin and end with A in some case; Akash begins with A but ends in h, so it is correctly rejected — that word is in the list precisely to catch a careless condition.
w[] String[10] - the ten words entered by the user f char - first character of the current word l char - last character of the current word i int - loop variable sc Scanner - object used to read input