2016-03-21 81 views
0

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

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); 
    } 
} 

对不起,我有点乱码,我一般都清理当一个程序完成并工作。

+3

欢迎堆栈溢出。在发布问题之前清理代码是一个好主意,理想的情况是将其降低到[mcve]。目前,我们知道有一个“输入异常错误”,但不是在哪里,或者是什么信息等等。我强烈建议您将代码简化为一个简单的例子,将错误也包含在问题中,并且你为了诊断而试过的东西。你可能会发现,在这样做的过程中,你解决了这个问题... –

回答

1

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

String normText = in.next(); 

应该

String normText = in.nextLine(); 

让整条生产线的输入textnext()如你预期的,因为

一个Scanner打破它的投入使用定界符模式, 它默认空白匹配的令牌不工作。

所以它匹配的只有第一个字,并试图解析下一个字作为int

一些其他点(因为你的下一行int caesarShift = in.nextInt();的):

    在你的加密/解密
  • 方法,你应该检查输入char是否是一个字母(例如使用Character.isLetter())并且只移动那些字符(目前,它不会在ALPHABET中找到空格,所以indexOf返回-1
  • 使用StringBuilder在循环连接字符串的时候,它的速度更快
+0

谢谢! in.nextLine完美解析 –