我想要一个java代码使用2个主要字符串加密给定字符串,如下所示
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();
}
答案 0 :(得分:2)
你几乎有了解决方案!问题是当你输入s2的最后3个字符中的一个时,你必须使用模运算符(当位置大于25时,你将到达字符串的末尾,并且必须在开头搜索! )
{CITY}
为了避免错误的用户输入,您应该检查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
中找不到该字符)并正确处理该情况(异常/ outprint +循环中断)
答案 1 :(得分:0)
您需要一个额外的循环来检查哪个字符与xcode-select --install
字符串匹配。除此之外,您必须使用s2
运算符来避免modulo
。
试试这个
ArrayIndexOutOfBound
<强>更新强>
正如@ ParkerHalo在评论中指出的那样,为了处理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();
}
,您可以像这样使用ArrayIndexOutOfBound
运算符
modulo