我即将完成一个接受用户输入并加密消息然后将其显示回来的程序。由于某种原因,我无法将字符串传递给我的加密方法并返回它。有人看出我哪里出了问题吗?
非常感谢所有回复的人!
public static String doEncryption(String s)
{
char alphabet[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z' };
char key[] = { 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'a' };
char encoded[] = new char[(s.length())];
String encrypted="";
int j=0;
for(int i=0; i<s.length(); i++){
//System.out.println(s.charAt(i));
boolean isFound = false;
j = 0;
while (j < alphabet.length && !isFound){
if (alphabet[j]==s.charAt(i)){
encrypted=encrypted+key[j];
isFound=true;
}
j++;
}
if(j>=alphabet.length){
encrypted=encrypted+s.charAt(i);
}
}
return (new String(encrypted));
}
public static void main(String args[])
{
String match = "QUIT";
String en = "";
System.out.println("Welcome to the Encoding Program!");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the text you want encoded below. Type QUIT when finished. ");
en = sc.nextLine();
String trim = en.substring(0, en.indexOf("QUIT"));
doEncryption(trim.toLowerCase());
//String en = doEncryption(sc.nextLine().toLowerCase());
System.out.println("The text is encoded as: " + trim.toUpperCase());
sc.close();
}
}
最佳答案
您的方法返回更新后的字符串,因此您需要在调用它时使用该返回值。变化:
doEncryption(trim.toLowerCase());
至
String updatedValue = doEncryption(trim.toLowerCase());
或者如果您愿意,可以重复使用trim
:
trim = doEncryption(trim.toLowerCase());
...然后使用 updatedValue
或 trim
显示结果。
关于java - 无法将字符串传递给 indexOf 之后的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29018690/