【发布时间】:2021-12-02 22:59:28
【问题描述】:
我正在尝试编写一个程序,该程序将使用 Vigenere 密码加密一个句子,但只有以辅音字母开头的单词,同时存储空格。 我对Java还不是很好,但是我写了一个方法来加密任何给定的单词(所有小写字母)我曾认为使用数组在需要的地方打印空格并忽略以元音开头的单词就足够了,但这样做实际上是每当我打印数组的第二个单词左右时给我错误的输出。有人可以指导我做错了什么吗?有没有更好的方法来做到这一点? 到目前为止,这是我的代码:
public class Main {
public static void main(String[] args) {
Scanner u = new Scanner(System.in);
final String k = u.next();
u.nextLine();
String message = u.nextLine();
String[] f = message.split(" ");
System.out.println(encipher(message,k));
for (String s : f) {
if (s.charAt(0) == 'a' || s.charAt(0) == 'e' || s.charAt(0) == 'i' ||
s.charAt(0) == 'o' || s.charAt(0) == 'u') {
System.out.println(s);
} else {
System.out.println(encipher(s, k));
}
}
}
public static String encipher(String message, final String key)
{
String output = "";
for (int x = 0, y = 0; x < message.length(); x++)
{
char c = message.charAt(x);
if (c < 'a' || c > 'z')
continue;
output += (char) ((c + key.charAt(y) - 2 * 'a') % 26 + 'a');
y = ++y % key.length();
}
return output;
}}
您可以看到正常输出(忽略空格和元音/辅音)和数组输出之间的区别。对于字符串键obi和字符串消息“olimpiada brasileira de informatica”,它应该打印“olimpiada psigjtsjzo em informatica”,但在数组中打印“olimpiada psigjtsjzo rf informatica”[暂时忽略打印行的事情,我会在我修复它正确加密]
【问题讨论】:
标签: java string encryption