我的程序會加密和解密Caesar Shift代碼,但現在我遇到的主要問題是我的用戶選擇無法正常工作。while循環導致打印語句打印兩次
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;
}
}
我不知道我看到的問題,你的'的System.out.println(「做出選擇:」);'裏面'while'循環,所以可以打印兩次,只要'Q'不是第一個輸入。 –
每當我希望用戶能夠從選項菜單中進行選擇時,如何讓它顯示? – user1713336