为什么我的程序跳过了replace方法?

时间:2019-01-29 05:09:22

标签: java

每当我运行下面的Java代码时,它都会编译,但是包含replace方法的行似乎被跳过,因此输入的字符串和输出(newMessage)相同。为什么?变量C和变量D是字符...

导入java.util.Scanner;

public class javaencrypt
{
    public static void main(String[] args)
        {
            // define and instantiate Scanner object
            Scanner input = new Scanner(System.in);

            //prompt user to enter a string
            System.out.println("Please enter a string: ");
            String message = input.nextLine();
            String newMessage = message;
            char c=' '; // the character at even locations
            char d=' '; // new character
            // go throughout the entire string, and replace characters at even positions by the character shifted by 5.
            // access the even characters with a for loop starting at 0, step 2, and ending at length()-1
            // for( initial value; maximum value; step)
            for(int k=0; k<message.length(); k=k+2)
            {
                c=message.charAt(k);
                d=(char)(c+5);
                /*
                    there will always be characters available, because keyboard is mapped on ASCII which is in the beginning of UNICODE
                */
                newMessage.replace(c,d);
            }
            System.out.println("Message replacement is: " + newMessage);
        }
}

1 个答案:

答案 0 :(得分:-1)

在Java中,字符串为immutable

  

一个不可变的类就是其实例无法修改的类。创建实例时实例中的所有信息都会初始化,并且无法修改该信息。

调用newMessage.replace(c, d);不会更新newMessage,而是创建一个新的String,其中所有字符c都替换为d。如果要更改newMessage以将c替换为d,则需要重新分配变量。看起来像newMessage = newMessage.replace(c, d);