Write a Java Program to accept a string from user, convert it into uppercase and then replace the vowels with the next character following it.
Hint:
Input: Computer
Output: CPMPVTFR
Answer:
import java.util.Scanner;
class Vowelreplace
{
public static void main(String[]args)
{
Scanner sr = new Scanner(System.in);
int i,len;
String word,newword = "";
char ch;
System.out.println("Enter a Word:");
word = sr.nextLine();
word = word.toUpperCase();
len = word.length();
for(i = 0;i<len;i++)
{
ch = word.charAt(i);
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
{
char nextchar = (char)(ch+1);
newword = newword+nextchar;
}
else
{
newword = newword+ch;
}
}
System.out.println("The converted string is:"+newword);
}
}
Demonstration:
2. A class namely Vowelreplace have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. To accept and store the word, a variable namely word has been defined of String data type.
6. Another variable namely newword has been declared for holding the converted string and a blank space has been assigned to it using "".
7. The variable ch will contain the individual characters in a string on basis of index positions.
8. A word has been demanded from user by giving a message.
9. The user input will get stored into word namely variable.
10. Then, the entered word will be converted to uppercase letters using string accessor method.
11. Then, length of the entered word will be stored in an integer variable namely len.
12. Then, a for loop will iterate and iteration will start for the variable namely i which is assigned with the value of 0. It means that loop will start from 0 index position and it will keep on executing till i doesn't reach less than length of the word.
13. In each loop iteration, ch will contain the individual character from the 1st index position.
14. Then, with the conditional statement, it will be determined if ch is containing any vowel or not.
15. Then, another character variable namely nextchar has been declared and with typecasting, character has been incremented by 1 which means, if any vowel is detected, then, that vowel will be added by 1 which in turn will display next character following that vowel.
16. Then, newword variable will add the previous blank space with the value at nextchar.
17. If any vowel doesn't gets detected, then the statement at the else block will get executed.
18. Finally, the entire converted word gets stored in newword variable which has been displayed outside the if...else block as it can be seen in the program.
Now, write this program and test it with various words and increase your knowledge.
Happy Coding.......