import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
/**
This class encrypts files using the Caesar cipher.
For decryption, use an encryptor whose key is the
negative of the encryption key.
*/
public class CaesarCipher
{
private String keyWordString;
private String removeDuplicates(String word){
for (int i = 0; i < word.length(); i++) {
if(!keyWordString.contains(String.valueOf(word.charAt(i)))) {
keyWordString += String.valueOf(word.charAt(i));
}
}
return(keyWordString);
}
/**
Constructs a cipher object with a given key word.
@param aKey the encryption key
*/
public CaesarCipher(String aKeyWord)
{
keyWordString = removeDuplicates(keyWordString);
keyWordString = aKeyWord;
//create the mapping string
//keyWordString = removeDuplicates(keyWordString);
int moreChar = 26 - keyWordString.length();
char ch = 'Z';
for(int j=0; j<moreChar; j++)
{
keyWordString += ch;
ch -= 1;
}
System.out.println("The mapping string is: " + keyWordString);
}
/**
Encrypts the contents of a stream.
@param in the input stream
@param out the output stream
*/
public void encryptStream(InputStream in, OutputStream out)
throws IOException
{
boolean done = false;
while (!done)
{
int next = in.read();
if (next == -1)
{
done = true;
}
else
{
//int encrypted = encrypt(next);
int encrypted = encryptWordKey(next);
System.out.println((char)next + " is encrypted to " + (char)encrypted);
out.write(encrypted);
}
}
}
/**
Encrypts a value.
@param b the value to encrypt (between 0 and 255)
@return the encrypted value
*/
public int encryptWordKey(int b)
{
int pos = b % 65;
return keyWordString.charAt(pos);
}
}
當我要運行這段代碼它給我,說一個運行時錯誤:如何從字符串中刪除重複的字母?凱撒密碼
Exception in thread "main" java.lang.NullPointerException
at CaesarCipher.removeDuplicates(CaesarCipher.java:15)
at CaesarCipher.<init>(CaesarCipher.java:29)
at CaesarEncryptor.main(CaesarEncryptor.java:29)
比方說,我進入JJJJJJJavvvvvaaaaaaa
,我希望它產生Java和給我的加密代碼。爲了區別於已經問過的其他問題,我需要使用removeDuplicates方法來執行並輸出以打印JavaZYWW .....等。任何幫助或建議?我的幫助將不勝感激
提示:這樣的代碼對於執行TDD和JUnit/unittests是**完美**。你想要先寫好測試用例,明確指出你期望某種方法「輸出」;然後你編寫產品代碼以「實施」該測試用例。這允許您在某些代碼無法按預期工作時立即計算出來;而且您只需單擊一下即可運行失敗的測試用例的調試器。 – GhostCat
哦,我沒有意識到。但輸出結果應該是JavaZYXW ......等等。我嘗試使用removeDuplicates方法的不同位置的調試器,但它跳過它並沒有執行它。 – user3416645