-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.

mmking
  • 1,564
  • 4
  • 26
  • 36
fihdi
  • 145
  • 1
  • 1
  • 12

2 Answers2

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");
user253751
  • 57,427
  • 7
  • 48
  • 90
0

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

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70