while循环导致print语句打印两次

时间:2013-01-12 06:12:09

标签: java loops while-loop

我的程序对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;
}
}

1 个答案:

答案 0 :(得分:5)

使用

读取移位值时
shift = in.nextInt();

线尾保留在扫描仪中。在下一个循环迭代中,读取剩余的行结束,但由于没有找到有效的输入(1,2或Q),循环将再次运行。

要解决此问题,请按以下方式阅读您的班次值:

shift = in.nextInt();
in.nextLine();