我正在尝试创建一个基本的加密程序,将字符值转换为数字形式,添加“密钥”,然后将它们转换回字符形式,从而加密单词。
但是我不知道如何使数值为 90 或更大(char Z),循环回 65(char A)。
public class Encode {
/**
* Main method - this does not need to be changed at all.
*/
public static void main(String[] args) {
testing();
userInteraction();
}
/**
* This method is used to test the encrypt method.
*/
public static void testing() {
String testMessage1 = "test";
int testKey1 = 11;
String result = encrypt(testMessage1, testKey1);
System.out.println("Encrypted result: "+result);
}
/**
* This method changes each character in a String to a
* different character based on the key passed in as
* an integer. The new String created by the encryption
* process is returned.
*
* @param message the String to be encoded
* @param key the integer value used for encryption
* @return a new encoded String
*/
public static String encrypt(String message, int key) {
System.out.println("encoding: "+message+", with key: "+key);
String encodedMessage = "";
message=message.toUpperCase();
int length = message.length();
for(int i=0;i<length;i++)
{
int characterValue = (int)message.charAt(i);
characterValue = characterValue + key;
if(characterValue>90)
{
characterValue = (65 + key ); // <---- What needs to go here? In order to make value loop back to A.
}
char myChar = (char)characterValue;
encodedMessage=encodedMessage+myChar;
}
return encodedMessage;
}