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?
CodePudding user response:
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.
CodePudding user response:
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);
}
}
CodePudding user response:
Can you try writing your name in lowercase and replacing F with the lowercase f, some languages support casing poorly.