0
我試圖從掃描儀和文件讀取器使用文件讀取,但我不知道爲什麼我的代碼沒有將字符放入HashBiMap中?如何從文件讀取到HashBiMap
public class MappedCharCoder implements CharCoder {
private HashBiMap<Character, Character> codeKey = HashBiMap.create(26);
/**
* The constructor takes a FQFN and reads from the file placing the contents
* into a HashBiMap for the purpose of encryption and decryption.
*
* @param map
* The variable map is the file name
* @throws FileNotFoundException
* If the file does not exist an exception will be thrown
*/
public MappedCharCoder(String map) throws FileNotFoundException {
HashBiMap<Character, Character> code = this.codeKey;
FileReader reader = new FileReader(map);
Scanner scanner = new Scanner(reader);
while (scanner.hasNextLine()) {
int x = 0;
int y = 1;
String cmd = scanner.next();
cmd.split(",");
char[] charArray = cmd.toCharArray();
char key = charArray[x];
if (code.containsKey(key)) {
throw new IllegalArgumentException(
"There are duplicate keys in the map.");
}
char value = charArray[y];
if (code.containsValue(value)) {
throw new IllegalArgumentException(
"There are duplicate values in the map.");
}
code.forcePut(key, value);
x+=2;
y+=2;
}
scanner.close();
if (code.size() > 26) {
throw new IllegalStateException(
"The hashBiMap has more than 26 elements.");
}
}
@Override
public char encode(char charToEncode) {
char encodedChar = ' ';
if (this.codeKey.containsKey(charToEncode)) {
encodedChar = this.codeKey.get(charToEncode);
return encodedChar;
} else {
return charToEncode;
}
}
@Override
public char decode(char charToDecode) {
char decodedChar = ' ';
if (this.codeKey.containsValue(charToDecode)) {
this.codeKey.inverse();
decodedChar = this.codeKey.get(charToDecode);
return decodedChar;
} else {
return charToDecode;
}
}
}
正如你可以從代碼中看到的,我試圖創建一個替換密碼。如果你們能幫助我讓這個班級工作,希望我能夠讓其他班級工作。非常感謝。
你期待cmd.split(「,」)這行是幹什麼的? (如果答案是「沒有」,那麼很好:你的期望符合實際情況。) –
感謝您的回覆。文件中的行讀取A,K等。第一個字符是用逗號分隔的鍵,然後是值。我認爲split()將字符串分隔成兩個字符串。你能告訴我如何解決這個問題嗎? – Ashton
'cmd.split(「,」)'返回一個'String'數組。如果你不對數組返回任何東西,那麼它就等於不做任何事情。 –