Categories
Class 10 Class 11 Class 12

Replace Consonants with the Previous Letters in Java

Write a program to input a sentence. Create a new sentence by replacing each consonant with the previous letter. If the previous letter is a vowel, then replace it with the next letter (i.e. if the letter is B then replace it with C as the previous letter is A) and the other characters remains the same. Display the new sentence.

Example:
INPUT: THE CAPITAL OF INDIA IS NEW DELHI.
OUTPUT: SGE BAQISAK OG IMCIA IR MEV CEKGI.

import java.io.*;
class Consonants{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Sentence: ");
        String s = br.readLine();
        s = s.toUpperCase();
        String t = "";
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetter(ch)){
                if(isVowel(ch))
                    t += ch;
                else{
                    char p = (char)(ch - 1);
                    if(isVowel(p))
                        t += (char)(ch + 1);
                    else
                        t += p;
                }
            }
            else
                t += ch;
        }
        System.out.println(t);
    }
    public static boolean isVowel(char ch){
        switch(ch){
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
            return true;
            default:
            return false;
        }
    }
}

Leave a Reply