我的程序加密和解密 Caesar Shift 代码,但我现在遇到的主要问题是我的用户选择无法正常工作。
import java.util.Scanner;
public class CaesarShiftTester
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
String message = "";
String userChoice = "";
int shift = 0;
System.out.println("1 - Encrypt\n2 - Decrypt\nQ - Quit Program");
while(!userChoice.equalsIgnoreCase("Q"))
{
System.out.println("Make a selection: ");
userChoice = in.nextLine();
if(userChoice.equalsIgnoreCase("1"))
{
System.out.print("Please enter a message to be encrypted: ");
message = in.nextLine();
System.out.print("Please enter a shift value for the cipher(0 - 25): ");
shift = in.nextInt();
CaesarShiftEncryption.genCipherAlphabet(shift);
System.out.println(CaesarShiftEncryption.encrypt(message));
}
else if(userChoice.equalsIgnoreCase("2"))
{
System.out.print("Please enter a message to be decrypted: ");
message = in.nextLine();
System.out.print("Please enter a shift value for the cipher(0 - 25): ");
shift = in.nextInt();
}
else if(userChoice.equalsIgnoreCase("Q"))
{
System.out.println("Thanks for using the program!");
}
}
}
}
在第一次通过程序后,“进行选择”被打印两次。这是类中的另一个文件,它在问题中没有那么大的作用,但是如果您想自己测试这些文件,就在这里。请注意,我还没有实现解密,所以现在只有“1”和“Q”选项实际上可以做任何事情。
public class CaesarShiftEncryption
{
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private static String newAlphabet = "";
public CaesarShiftEncryption()
{
}
public static String genCipherAlphabet(int shift)
{
for(int i = 0; i < ALPHABET.length(); i++)
{
int alphabetShift = i + shift;
alphabetShift = alphabetShift % 26;
newAlphabet += ALPHABET.charAt(alphabetShift);
}
return newAlphabet;
}
public static String encrypt(String message)
{
int letter = 0;
String encoded = "";
char[] messageLetters = new char[message.length()];
for(int i = 0; i < message.length(); i++)
{
messageLetters[i] = message.charAt(i);
}
for(int a = 0; a < message.length(); a++)
{
if(Character.isWhitespace(messageLetters[a]))
{
encoded += " ";
a++;
}
if(Character.isUpperCase(messageLetters[a]))
messageLetters[a] = Character.toLowerCase(messageLetters[a]);
letter = ALPHABET.indexOf(messageLetters[a]);
encoded += newAlphabet.substring(letter, letter + 1).toUpperCase();
}
return encoded;
}
}