我的程序加密和解密 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;
}
}
最佳答案
当您读取移位值时
shift = in.nextInt();
行尾保留在扫描仪中。在下一次循环迭代中,将读取剩余的行尾,但由于没有找到有效的输入(1,2 或 Q),因此循环将再次运行。
要解决这个问题,请像这样读取您的移位值:
shift = in.nextInt();
in.nextLine();
关于java - While 循环导致 print 语句打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14290807/