[英]Simple encryption of a String in Java
我想编写一个程序,该程序将使用一个String并将2添加到String的每个字符中,这很简单这是我的代码。 例:-
String str="ZAP YES";
nstr="BCR AGU" //note Z=B and Y=A
String str=sc.nextLine();
String nstr=""
for(int i=0;i<str.length();i++)
{
char ch=sc.charAt(i);
if(ch!=' ')
{
if(ch=='Z')
ch='B';
else if(ch=='Y')
ch='A';
else
ch=ch+2;
}
nstr=nstr+ch;
}
现在我想将每个字符增加n(而不是2),而这确实是我无法解决的。
我可能会考虑使用n%26,并为条件使用循环,但是我无法解决如何实现该问题。
使用% 26
是正确的主意。 缺少的部分是您的范围不是从零开始的。 您可以通过减去“ A”(即将“ A”视为0,将“ B”视为1,以此类推)来模拟从零开始的范围,然后读取它:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ') {
ch = (char)((ch - 'A' + n) % 26 + 'A');
}
nstr += ch;
}
你必须:
例:
public static char increment(char c, int n) {
return (char) (((c - 'A') + n) % 26 + 'A');
}
public static void main(String[] args) {
System.out.println(increment('Z', 1)); // returns 'A'
System.out.println(increment('Z', 2)); // returns 'B'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.