如何从文件读取到HashBiMap

时间:2013-10-08 19:20:06

标签: java filereader

我正在尝试使用扫描程序和文件阅读器从文件中读取,但我不知道为什么我的代码没有将字符放入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;
    }
}

}

从代码中可以看出,我正在尝试创建替换密码。如果你们能帮助我上课,希望我能够让其他班级工作。非常感谢。

1 个答案:

答案 0 :(得分:0)

cmd.split(",")会返回String[],但您会立即放弃该结果。

你可能想要的东西更接近

String[] chars = cmd.split(",");
char key = chars[0].charAt(0);
char value = chars[1].charAt(0);
// all the other checking you do

此外,如果值已经在地图中,FWIW HashBiMap将已经抛出IllegalArgumentException。 (但不是为了钥匙。)