我需要一个java代码来使用两个主字符串加密给定的字符串,如下所示
s1 = "qwertyuiopasdfghjklzxcvbnm";
s2 = "mnbvcxzasdfghjklpoiuytrewq";如果我们的输入字符串是"mnb",那么它将与s2进行比较,并在s1中添加相同的索引3,那么输出将是"rty",但我没有得到正确的输出。
有人能帮我解决这个问题吗?
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for(int i=0;i<s2.length();i++){
if(input.charAt(i)==s2.charAt(i)){
out+=s1.charAt(i+3);
}
System.out.println(out);
}
sc.close();
}发布于 2015-12-04 13:17:55
您需要一个额外的循环来检查来自s2 string.Other的哪一个字符匹配,而不是这样,您将不得不使用modulo操作符来避免ArrayIndexOutOfBound。
尝尝这个
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input, out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (input.charAt(i) == s2.charAt(j)) {
out += s1.charAt((j + 3)%26);
}
}
}
System.out.println(out);
sc.close();
}更新
正如@ParkerHalo在注释中指出的那样,要处理ArrayIndexOutOfBound,可以像这样使用modulo操作符
out += s1.charAt((j + 3)%26);发布于 2015-12-04 13:18:04
你差点就找到解决办法了!问题是,当您输入s2的最后3个字符之一时,必须使用模运算符(当位置大于25时,您将到达字符串的末尾,必须在开始时开始搜索!)
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
int position = s2.indexOf(input.charAt(i));
position = (position + 3) % 26;
out = out + s1.charAt(position);
}
sc.close();
}为了避免错误的用户输入,您应该检查position是否为-1 (如果在s2中找不到字符),并正确处理这种情况(异常/输出+循环中的中断)
https://stackoverflow.com/questions/34089088
复制相似问题