Write a program to accept a word and print the Symbolic of the accepted word. Symbolic word is formed by extracting the characters from the first consonant, then add characters before the first consonant of the accepted word and end with "TR". Example: AIRWAYS - Symbolic word is RWAYSAITR BEAUTY - Symbolic word is BEAUTYTR
Topic: String manipulation — Symbolic word
Answer
import java.util.Scanner;
class Symbolic { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a word : "); String w = sc.next().toUpperCase();
int pos = -1; char ch;
for(int i = 0; i < w.length(); i++) { ch = w.charAt(i); if(ch != 'A' && ch != 'E' && ch != 'I' && ch != 'O' && ch != 'U') { pos = i; break; } }
if(pos == -1) System.out.println("The word has no consonant."); else { String sym = w.substring(pos) + w.substring(0, pos) + "TR"; System.out.println("Symbolic word is " + sym); } } }
Break the rule into three pieces and the program almost writes itself:
- find the position of the first consonant
- take the word from that position to the end
- add the part before it, then "TR"
Finding the first consonant: loop from index 0, and the first character that is NOT a vowel is it. Store its index and break immediately — without the break you would end up with the LAST consonant instead.
Then the rearrangement is a single line built from two substring calls: w.substring(pos) - from the first consonant to the end w.substring(0, pos) - everything before it (empty if pos is 0) joined together and followed by "TR".
Trace AIRWAYS: A and I are vowels, R at index 2 is the first consonant. substring(2) is "RWAYS", substring(0, 2) is "AI", so the answer is RWAYS + AI + TR = RWAYSAITR. Trace BEAUTY: B at index 0 is already a consonant. substring(0) is the whole word and substring(0, 0) is empty, giving BEAUTY + "" + TR = BEAUTYTR. Both match the examples — note how the empty second piece handles that case automatically, with no special code needed.
w String - the word entered, converted to upper case ch char - holds each character while searching for a consonant pos int - index of the first consonant, or -1 if none exists sym String - the Symbolic word that is built up i int - loop variable sc Scanner - object used to read input