【问题标题】:Why does my program skip over the replace method? [duplicate]为什么我的程序会跳过替换方法? [复制]
【发布时间】:2019-06-22 04:12:31
【问题描述】:

每当我运行下面的 java 代码时,它都会编译,但包含替换方法的行似乎被跳过了,这样输入的字符串和输出 (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);
        }
}

【问题讨论】:

  • 因为您没有再次分配 newMesssage 的值,因为字符串在类似 newMesssage = newMessage.replace(c,d); 中是不可变的
  • 因为 replace 方法正在返回新的 String 对象。您应该分配其返回对象以使其保持更新,例如 newMessage=newMessage.replace(c,d)。

标签: java


【解决方案1】:

在 Java 中,字符串是 immutable

不可变类只是一个实例不能被修改的类。实例中的所有信息都是在创建实例时初始化的,不能修改信息。

当您调用newMessage.replace(c, d); 时,这不会更新newMessage,而是创建一个新的String,并将所有字符c 替换为d。如果您希望newMessage 更改为包括将c 替换为d,那么您需要重新分配变量。这看起来像newMessage = newMessage.replace(c, d);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多