Caesar Shift Cipher,输入异常错误

时间:2016-03-21 14:20:33

标签: java encryption input

我最初遇到了一些问题,但在这里找到了一些不同的帮助。现在我似乎遇到输入异常错误的问题。我相信我的输入格式正确。

import java.util.Scanner;
public class CaesarShift
{
//initialize private string for the alphabet
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//public encryption code
public String encryptionMethod(String normText, int caesarShift)
{
    normText = normText.toLowerCase();
    String cipherText = "";
    for (int a = 0; a < normText.length(); a++)
    {
        int charP = ALPHABET.indexOf(normText.charAt(a));
        int shiftValue = (caesarShift + charP) % 26;
        char replaceValue = this.ALPHABET.charAt(shiftValue);
        cipherText += replaceValue;
    }
    return cipherText;
}
public String decryptionMethod(String cipherText,int caesarShift)
{
    cipherText = cipherText.toLowerCase();
    String normText = "";
    for (int a = 0; a < cipherText.length(); a++)
    {
        int charP = this.ALPHABET.indexOf(cipherText.charAt(a));
        int keyValue = (charP - caesarShift) % 26;
        if(keyValue < 0)
        {
            keyValue = this.ALPHABET.length() + keyValue;
       }
       char replaceValue = this.ALPHABET.charAt(keyValue);
       normText += replaceValue;
    }
    return normText;
}

}

然后我有测试器方法,我遇到输入异常错误的实际问题

import java.util.Scanner;
public class CaesarShiftTester
{
public static void main(String args[])
{
    //import of the scanner method to ask the user for the input they would like
    Scanner in = new Scanner(System.in);
    System.out.println("What is the text you would like to do something with?");
    String normText = in.next();
    System.out.println("What is the Caesar Shift Value?");
    int caesarShift = in.nextInt();
    //new declaration of the CaesarShift class to report back to easily
    CaesarShift shift = new CaesarShift();
    //decalre the need properties for the encryption
    String cipherText = shift.encryptionMethod(normText, caesarShift);
    System.out.println("Your normal text is: " + normText);
    System.out.println("Your text after encryption is: " + cipherText);
    String cnormText = shift.decryptionMethod(cipherText, caesarShift);
    System.out.println("Your encrypted text is: " + cipherText);
    System.out.println("Your decrypte text is: " + cnormText);
    }
}

对于有些混乱的代码感到抱歉,我通常会在程序完成并正常工作时进行清理。

1 个答案:

答案 0 :(得分:1)

如果您只输入1个单词,您的程序应该可以正常工作。如果包含空格,则会出现异常。问题在线

String normText = in.next();

应该是

String normText = in.nextLine();

将整行作为输入textnext()无效,因为

  

Scanner使用分隔符模式将其输入分解为标记,   默认情况下匹配空格

因此,它仅匹配第一个单词,并尝试将下一个单词解析为int(因为您的下一行int caesarShift = in.nextInt();

其他一些观点:

  • 在您的加密/解密方法中,您应该检查输入char是否是一个字母(例如使用Character.isLetter())并仅移动那些字符(目前,它不会在{{ 1}}所以ALPHABET返回indexOf
  • 在循环中连接字符串时使用-1,它更快
相关问题