I am taking an intro level java programming class and i am a little stuck at the moment. I'm trying to use a the replace method. My objecti with this program is to gather a phrase from the user and then have it print the same phrase with some characters replaced. The Specific characters are 'a' to '@', 'e' to '3', 'i' to '!', 'o' to '0', 'b' to '8', and ' ', to '_'. I am keeping this as basic as possible so any comments I would appreciate if you keep in mind that anything too much more complex than what i have here will probably not be what i'm looking for. But please anything you can think of, whether it helps or not, will be much appreciated.

import java.util.Scanner;
public class Mutator
{
    public static void main (String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Which of our presidents freed the slaves?");
        String phrase = keyboard.nextLine();


        phrase.replace('a','@');
        phrase.replace('e','3');
        phrase.replace('i','!');
        phrase.replace('o','0');
        phrase.replace('b','8');
        phrase.replace(' ','_');


        System.out.println(phrase);
    }
}

Recommended Answers

All 4 Replies

Remember that replace() returns a string. It doesn't modify the string that called it directly, but rather it makes a new String object. You're really close, but you need to keep that in mind.

So do I need to create a new variable for each character I'm replacing?

do I need to create a new variable

Try it and see what happens. You'll need a print statement for each variable.

I suggest to put it to the same variable.

phrase = phrase.replace('a', '@');
commented: Yes! that was exactly what i needed. That got me right where i wanted to be. Thanks for your help!! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.