我正在尝试创建一个加密方案,用相应的字母替换String
中的字母。
例如,在字符串“apple”中,“a”被替换为“k”,依此类推。每个字母都有固定对应的字母。
我想获取用户输入并将其存储到数组中。
然后我想循环遍历数组并找到 String
的每个索引。然后将每个索引替换为相应的字母。
这是我到目前为止所做的,但我无法运行代码。我主要得到的是,错误:不兼容的类型
。
我无法确定是否应该使用 charAt
方法并将变量类型更改为 char。
import java.util.*;
public class Encrypt {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the String Name to encrypt:");
String inputString = input.nextLine();
String[] str = new String[inputString];
replaceString();
}
public static void replaceString() {
for(int i = 0; i < str.length(); i++) {
if(str.indexOf(i) == "a") {
str.indexOf(i) = "k";
} else if(str.indexOf(i) == "b") {
str.indexOf(i) = "n";
}
//and so on A-Z...
System.out.print(str);
}
}
}
最佳答案
为什么要使用String[]
? IMO 你应该使用 char[]
并且以下代码将执行你想要的操作:
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("Enter the String Name to encrypt:");
String inputString = input.nextLine();
char[] str = inputString.toCharArray();
replaceString(str);
}
public static void replaceString(char[] str) {
int length = str.length;
for(int i = 0; i < length; i++) {
if(str[i] == 'a') {
str[i] = 'k';
} else if(str[i] == 'b') {
str[i] = 'n';
}
}
System.out.println(Arrays.toString(str));
System.out.println(String.valueOf(str));
}
运行程序:
Enter the String Name to encrypt: bat
[n, k, t] nkt
关于java - 如何替换数组中的字符串字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32815464/