gpt4 book ai didi

java - 如何循环回到字符串的开头? super 技能,加密-解密

转载 作者:行者123 更新时间:2023-11-30 01:41:35 24 4
gpt4 key购买 nike

我正在做 Hyperskill 加密 - 解密项目,描述如下,我遇到了问题。例如,如果我尝试加密字母 = a key = 1,则效果很好,输出将是:b。但如果 letter = z, key = 1,则该方法将不起作用,该方法应循环回到字母表的开头,并且输出应为 a。问题是 - 如果必须这样做,我怎样才能让我的方法循环回到开头?

项目描述:

Write a program that reads an English message and an integer number (key) from the standard input and shifts each letter by the specified number according to its order in the alphabet. If you reach the end of the alphabet, start back at the beginning (a follows z).

The English alphabet is below: abcdefghijklmnopqrstuvwxyz

The program should not modify non-letter characters. The key is assumed to mean that if a person knows the value of the key, he or she will be able to decrypt the text, and if he or she does not know, he or she will not be able to decrypt the text. It's like a real key that can open up access to the message text.

public static void encrypt(String input, int key) {
String output = "";
String alphabet = "abcdefghijklmnopqrstuvwxyz";

for (int i = 0; i < input.length(); i++) {
String inputCharacter = Character.toString(input.charAt(i));
if (inputCharacter.equals(" ")) {
output += " ";
}
for (int j = 0; j < alphabet.length(); j++) {
String alphabetCharacter = Character.toString(alphabet.charAt(j));
String decryptedCharacter = Character.toString(alphabet.charAt(j) + key);

if (inputCharacter.equals(alphabetCharacter)) {
output += decryptedCharacter;
}

}
}
System.out.println(output);


}

最佳答案

您可以使用模运算符 % 将大索引“环绕”到字符串的长度:

String decryptedCharacter = Character.toString(alphabet.charAt((j + key) % alphabet.length()));

(请注意括号:在原始代码中,您将 key 添加到 char,而不是索引。)

此外,您还可以使用 contains 来检查字符是否在字母表中以处理例如标点符号:

if (! alphabet.contains(inputCharacter)) {
output += inputCharacter;
}

关于java - 如何循环回到字符串的开头? super 技能,加密-解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59751552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com