-2

I want to create a small program where I can enter a string using a scanner, and replace characters. For example, every "a" in the string should be replaced with a "4".

I have this sourcecode:

Scanner s = new Scanner(System.in);
String string = s.nextLine();
System.out.println("Your old text:" + original_string);

string.replace("i", "1");      
string.replace("a", "4");
System.out.println("Your new super awesome text: " + string);

For example, if I input "ia", it should return "14". Unfortunately, this does not happen.

0

2 Answers 2

5

String.replace doesn't modify the original String. Indeed, Strings can't be modified - all that can happen is that something creates a slightly different String and returns it.

string = string.replace("i", "1");
string = string.replace("a", "4");
Sign up to request clarification or add additional context in comments.

Comments

0

You have to reassign the value of the string to the replaced string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.