-2

I am a beginner in java and am having trouble with printing out userinput with charAt(). I need to create a program that takes userinput and adds "op" before vowels in that text. (example: Userinput -> "Beautiful" would be translated as "Bopeautopifopul") I am struggling to figure how to write this. So far I have come up with this small bit.

import java.util.Scanner;
public class oplang {
static Scanner userinput = new Scanner(System.in);
public static void main(String[] args) {

    char c ='a';
    int n,l;

    System.out.println("This is an Openglopish translator! Enter a word here to translate ->");
    String message = userinput.nextLine();
    System.out.println("Translation is:");
    l = message.length();

    for (n=0; n<l; n++);
    {
        c = message.charAt();
        if (c != ' ');
    {
        System.out.println(" ");
    }
    c++;
}
}}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
CMCK
  • 1
  • 1

1 Answers1

1

I would use a regular expression, group any vowels - replace it with op followed by the grouping (use (?i) first if it should be case insensitive). Like,

System.out.println("Translation is:");
System.out.println(message.replaceAll("(?i)([aeiou])", "op$1"));

If you can't use a regular expression, then I would prefer a for-each loop and something like

System.out.println("Translation is:");
for (char ch : message.toCharArray()) {
    if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) {
        System.out.print("op");
    }
    System.out.print(ch);
}
System.out.println();

And, if you absolutely must use charAt, that can be written like

System.out.println("Translation is:");
for (int i = 0; i < message.length(); i++) {
    char ch = message.charAt(i);
    if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) {
        System.out.print("op");
    }
    System.out.print(ch);
}
System.out.println();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249