2016-03-21 21 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完美解析 –