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);

     }
   }
4

3 回答 3

1

尝试:

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

字符串在 Java 中是不可变的(无法修改),该replace方法不会影响您调用它的变量,但会返回一个带有所做更改的新字符串。

于 2013-10-13T19:14:54.753 回答
0

你误解了到底在input.replace做什么!它创建新字符串,在新字符串中替换它,然后用替换字符返回新字符串。

这是你需要做的:

input = input.replace(convert[0][i], convert [1][i]);
于 2013-10-13T19:15:27.093 回答
0

String.replace()函数只返回一个新字符串,而不影响调用它的字符串。更改input.replace(convert[0][i], convert [1][i]);input = input.replace(convert[0][i], convert [1][i]);

于 2013-10-13T19:14:44.547 回答