Computer Applications

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 of B is A). Other characters must remain the same. Display the new sentence.
Sample Input     : ICC WORLD CUP
Sample Output  : IBB VOQKC BUQ

Java

Java String Handling

23 Likes

Answer

import java.util.Scanner;

public class KboatReplaceLetters
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        System.out.println("Enter a sentence: ");
        String str = in.nextLine();      
        
        int len = str.length();
        
        String newStr = "";
                
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            char chUp = Character.toUpperCase(ch);
            if (chUp == 'A' 
                || chUp == 'E' 
                || chUp == 'I' 
                || chUp == 'O' 
                || chUp == 'U') {
                newStr = newStr + ch;
            }
            else {
                char prevChar = (char)(ch - 1);
                char prevCharUp = Character.toUpperCase(prevChar);
                if (prevCharUp == 'A' 
                    || prevCharUp == 'E' 
                    || prevCharUp == 'I' 
                    || prevCharUp == 'O' 
                    || prevCharUp == 'U') {
                    newStr = newStr + (char)(ch + 1);
                }
                else {
                    newStr = newStr + prevChar;
                }
            }
        }
        
        System.out.println(newStr);
        
    }
}

Variable Description Table

Program Explanation

Output

Answered By

5 Likes


Related Questions