2 回答

TA貢獻(xiàn)1863條經(jīng)驗 獲得超2個贊
map<Character,Integer> enc = new map<Character,Integer>();
Map是 Java 中的一種接口類型,不能被實例化[作為匿名內(nèi)部類以外的任何東西]。您需要實例化實現(xiàn)的類型之一Map,例如TreeMapor HashMap。
//Since Java 7, <> infers the type arguments
Map<Character, Integer> enc = new HashMap<>();
enc[input.charAt(i)] = i;
您使用的括號運(yùn)算符語法 ( enc[input.charAt(i)]) 是 C++ 原生的,在 Java 中不可重載;因此,Java 中唯一允許使用此類括號的情況是在使用數(shù)組時。
您需要使用get()和put()配合 java 地圖。
enc.put(input.charAt(i), i);
//...
int pos = enc.get(msg.charAt(i) - 32);

TA貢獻(xiàn)1998條經(jīng)驗 獲得超6個贊
老問題,但供將來參考,這里是解決方案:
String plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String ABC(String msg, String input)
{
// Hold the position of every character (A-Z) from encoded string
Map<Character, Integer> enc = new HashMap<>();
for (int i = 0; i < input.length(); i++)
{
des.put(input.charAt(i), i);
}
String decipher = "";
// This loop deciphered the message.
// Spaces, special characters and numbers remain same.
for (int i = 0; i < msg.length(); i++)
{
if (msg.charAt(i) >= 'a' && msg.charAt(i) <= 'z')
{
int pos = enc.get((char)(msg.charAt(i)-32));
decipher += plaintext.charAt(pos);
}
else if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z')
{
int pos = enc.get(mensaje.charAt(i));
decipher += plaintext.charAt(pos);
}
else
{
decipher += msg.charAt(i);
}
}
return decipher;
}
基本上你必須put在映射時使用,然后get在使用時使用它。哦,從 char 中減去它。
添加回答
舉報