【发布时间】: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