它将反转纯文本,用' * '替换空白,然后根据加密密钥移动纯文本的字母


public class pppp {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String s1;
s1=input.nextLine();
char ch[]=new char[s1.length()];
int x;
x=input.nextInt();
int i=0;
int j=0;
int h=0;
for(i=s1.length()-1;i>=0;i--) {
ch[j]=s1.charAt(i);
j++;
}
System.out.println(ch);
for(i=0;i<s1.length();i++) {
if(ch[i]==' ') {
ch[i]='*';
}
else if((ch[i]+x)<122 && ch[i]!='*') {
ch[i]+=x;
}
else if((ch[i]+x-'z')==1) {
ch[i]='a';
}
else if(ch[i]+x-'z'>1) {
ch[i]='a';
ch[i]+=((ch[i]+x-'z')-1);
}
}

System.out.println(ch);
}
}

当我试图打印" megdeth "并给出键7,它将根据这个键来移动t的位置,THIS '{'出现。

megadeth
7
htedagem
o{lkhnlt

它现在对t有效,但如果我写u而不是t,它会得到N,这是错误的。这是编辑后的代码。

我能做些什么来修复它?

你想:

  1. 反转字符串
  2. '*'
  3. 替换所有出现的空格字符(' ')
  4. 对结果字符串
  5. 中的字母执行凯撒键移位

你可以这样使用streams:

import java.util.Scanner;
import java.util.stream.Collectors;
public class pppp {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String s1;
s1=input.nextLine();
int x;
x=input.nextInt();
System.out.println(
new StringBuilder(s1)
.reverse().toString()
.chars()
.map(c -> c == ' ' ? '*' : c)
.map(c -> {
if (Character.isLetter(c)) {
char first = Character.isUpperCase(c) ? 'A' : 'a';
return first + (((c - first) + x) % 26);
}
else return c;
})
.mapToObj(c -> Character.toString((char) c))
.collect(Collectors.joining())
);
}
}

下面是计算移位的相关代码片段:

char first = Character.isUpperCase(c) ? 'A' : 'a';
return first + (((c - first) + x) % 26);

假设你想把字母t移动7个位置。结果应该是a

要做到这一点,让我们首先计算字母t在字母表中的索引(从零开始):

index = 't' - 'a' = 116 - 97 = 19

接下来,将key加到index模数26中,得到被key移动的字母的索引。在本例中,键为7。

shiftIndex = (index + 7) % 26 = (19 +7) % 26 = 26 % 26 = 0 

最后,您可以像这样计算移位字符:

result = 'a' + shiftIndex = 'a' + 0 = 'a'

这就是我的解决方案所做的,加上大写字母的附加逻辑。

最新更新