我需要编写一个程序,获取一个人的名字、中间名和姓氏并对其进行加密:用户输入的每个字母都由选定的密钥循环移动。例如,如果密钥为 1,原始字母为“A”,则加密后的字母为“B”。如果密钥为 3,原始字母为“b”,则加密后的字母为“e”。如果密钥为 3,原始字母为“z”,则加密后的字母为“c”。
这是我的代码:
import java.util.Scanner;
public class Cipher {
public static void main(String []main){
Scanner console = new Scanner(System.in);
System.out.print("Enter your first name: ");
String firstname = console.nextLine();
System.out.print("Enter your middle name: ");
String middlename = console.nextLine();
System.out.print("Enter your last name: ");
String lastname = console.nextLine();
System.out.print("enter the key ");
int N = console.nextInt();
String s = firstname + middlename + lastname;
System.out.print("your original name is "+ s);
String empty = "";
for( int i = 0; i<=s.length();i++){
if (s.charAt(i)!=' '){
System.out.print(empty ="" + s.charAt(i));
}
else{
System.out.print(empty +=s.charAt(i+N));
}
}
System.out.print("encrypted name is " + empty);
}
}
我的问题似乎在循环中,但我不知道如何解决它。
我得到了什么:
Enter your first name: a
Enter your middle name: b
Enter your last name: c
enter the key 2
your original name is abcaababcException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at test1.test.main(test.java:19)
虽然我应该得到例如以下内容:
Enter your first name: a
Enter your middle name: b
Enter your last name: c
enter the key 2
your original name is abc
encrypted name is cde