0

I'm trying to print ooed (changing the name from Fred to ooed), but my program won't change the first letter ('F') while changing the rest.

String name  = "Fred";
String namea = name.replace('a', 'i');
String nameb = name.replace('n', 'i');
String namec = name.replace('r', 'o');
String named = name.replace('F', 'o');

       for(int i =0; i < 4; i++){
            switch(name.charAt(i)){
                case 'a':
                    name = namea;
                    break;
                case 'n':
                    name = nameb;
                    break;
                case 'r':
                    name = namec;
                    break;
                case 'F':
                    name = named;
                    break;
  }
 }
 System.out.println(name);

Anyone know what I'm doing wrong?

  • 2
    First of all in `F` `Fred` becomes `ored`, then in the second iteration `r` you are replacing `ored` with `Foed` - It is doing exactly the strange logic that you are telling it to do. – Scary Wombat Apr 13 '22 at 02:45

3 Answers3

1

You can simply replace the letter you want for the word (name) and reassign back the new value to the original variable (name). Step by step replace will give you the desired result.

Try the below code:

String name  = "Fred";
name = name.replace('a', 'i');
name = name.replace('n', 'i');
name = name.replace('r', 'o');
name = name.replace('F', 'o');
System.out.println(name);

Read more about string here, immutable string here.

Prog_G
  • 1,539
  • 1
  • 8
  • 22
0

Try using contains for comparisons, and make sure to differentiate the primitive data types.

String name = "Fred";
    
if(name.contains("F")) {
    String replaceName = name.replace('F','o');
    if(replaceName.contains("r")) {
        String final = replaceName.replace('r','o');
        System.out.println(final); 
    }
}
  • While this should _work_, `contains` is redundant here. `contains` and `replace` both perform a linear search, so it's doing more harm than good. – David Gish Apr 13 '22 at 04:20
-1

Can you try writing your name in lowercase and replacing F with the lowercase f, some languages support casing poorly.