0

By the way I am a beginner programmer so i don't really know what to do. This is what I tried but it just prints out the input without the letters being replaced.

  import java.util.Scanner;

  class converter {
  public static void main (String [] args){
  char[][] convert = new char [2][10];
  convert [0][0] = 'I' ;
  convert [0][1] = 'Z' ;
  convert [0][2] = 'E' ;
  convert [0][3] = 'A' ;
  convert [0][4] = 'S' ;
  convert [0][5] = 'G' ;
  convert [0][6] = 'L' ;
  convert [0][7] = 'B' ;
  convert [0][8] = 'P' ;
  convert [0][9] = 'O' ;
  convert [1][0] = '1' ;
  convert [1][1] = '2' ;
  convert [1][2] = '3' ;
  convert [1][3] = '4' ;
  convert [1][4] = '5' ;
  convert [1][5] = '6' ;
  convert [1][6] = '7' ;
  convert [1][7] = '8' ;
  convert [1][8] = '9' ;
  convert [1][9] = '0' ;

     Scanner sc = new Scanner(System.in);

     String input = sc.nextLine();
     for (int i = 0; i< 10; i++)
        input.replace(convert[0][i], convert [1][i]);
     System.out.print(input);

     }
   }
  • String is immutable, which means you can't change it, which means `input.replace(convert[0][i], convert [1][i]);` has no effect on `input`. However, the `replace` method will return a new String with the changes if you were to assign this String to another String reference, or even the `input` reference, you would see your changes. – Ray Stojonic Oct 13 '13 at 19:13

3 Answers3

1

Try:

input = input.replace(convert[0][i], convert [1][i]);

Strings are immutable (cannot be modified) in Java, the replace method does not affect the variable you call it against, but returns a new string with the changes made.

Steve
  • 7,171
  • 2
  • 30
  • 52
0

The String.replace() function just returns a new string without affecting the string on which it was called. Change input.replace(convert[0][i], convert [1][i]); to input = input.replace(convert[0][i], convert [1][i]);.

musical_coder
  • 3,886
  • 3
  • 15
  • 18
0

You misunderstanding what exactly is input.replace doing!. It creates new string, replaces it in the new string and then RETURN new string with replaces char.

This is what you need to do :

input = input.replace(convert[0][i], convert [1][i]);
libik
  • 22,239
  • 9
  • 44
  • 87