您好,我想创建一个表,说如果x=y
,则返回z。我知道我目前执行此操作的方法可能效率很低,但这是我入门的最佳方法。该程序是用于更改字母(即'a'='g'
,'b'='h'
)的简单密码程序。我希望能够控制哪些值等于什么,而不是执行移位/凯撒密码之类的操作。谢谢
import java.util.Scanner;
public class main {
public static String k;
public static void main(String[] args) {
TBL1 gg=new TBL1();
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Character");
String chr=sc.nextLine();
sc.close();
for(int i=1;i<=chr.length();i++){
k=TBL1.set2(Character.toString(chr.charAt(i-1)));
System.out.print(k);
}
}
}
public class TBL1 {
public static String chr;
public static String set2(String character){
if(character.equalsIgnoreCase("a")){
chr="b";
}else if(character.equalsIgnoreCase("b")){
chr="c";
}else if(character.equalsIgnoreCase("c")){
chr="d";
}else if(character.equalsIgnoreCase("d")){
chr="e";
}else if(character.equalsIgnoreCase("e")){
chr="f";
}else if(character.equalsIgnoreCase("f")){
chr="g";
}else if(character.equalsIgnoreCase("g")){
chr="h";
}else if(character.equalsIgnoreCase("h")){
chr="i";
}else if(character.equalsIgnoreCase("i")){
chr="j";
}else if(character.equalsIgnoreCase("j")){
chr="k";
}else if(character.equalsIgnoreCase("k")){
chr="l";
}else if(character.equalsIgnoreCase("l")){
chr="m";
}else if(character.equalsIgnoreCase("m")){
chr="n";
}else if(character.equalsIgnoreCase("n")){
chr="o";
}else if(character.equalsIgnoreCase("o")){
chr="p";
}else if(character.equalsIgnoreCase("p")){
chr="q";
}else if(character.equalsIgnoreCase("q")){
chr="r";
}else if(character.equalsIgnoreCase("r")){
chr="s";
}else if(character.equalsIgnoreCase("s")){
chr="t";
}else if(character.equalsIgnoreCase("t")){
chr="u";
}else if(character.equalsIgnoreCase("u")){
chr="v";
}else if(character.equalsIgnoreCase("v")){
chr="w";
}else if(character.equalsIgnoreCase("w")){
chr="x";
}else if(character.equalsIgnoreCase("x")){
chr="y";
}else if(character.equalsIgnoreCase("y")){
chr="z";
}else if(character.equalsIgnoreCase("z")){
chr="a";
}else if(character.equalsIgnoreCase(" ")){
chr=" ";
}
return chr;
}
}
String original = "abcdefghijk"
创建第二个字符串:String coded = "bcdefhijka";
,尽管在您的情况下位置会有所不同。
这样,您可以执行以下操作:public static void main(String[] args) {
String original = "abcdefghijk";
String coded = "bcdefghijka";
char c = coded.charAt(original.indexOf('c'));
System.out.println("c coded = " + c);
}
当然,您可以走得更远,并添加'if indexOf(char)== -1 return char'规则
遍历(重复)字符串中的所有字符;
k
(例如您的情况为1)执行移位,然后使用字母的大小(英语ABC为26)获取模数;StringBuilder
)。"reordered ABC".charAt(index);
现在有几件事:
从字符到索引的转换可以通过简单地减去字符值'A'
(char
是Java中的数字值;]
%
运算符是mod
方法:mod(int i, int n) = ((i % n) + n) % n
,以便正确处理负值;StringBuilder
实例,而无需进行加密/解密(特殊情况下需要特殊代码)。private static char getNextChar(char value) {
char a = 'a', z = 'z';
int shiftKey = 1;
if (Character.isLowerCase(value)){
int nextValue = value + shiftKey;
if (nextValue > z)
nextValue = a + nextValue % z;
return (char)nextValue;
}
return value;
}