我想出了下面的代码。设法解决了大多数错误,除了与 Map 相关的错误。
我知道下面这行代码属于 C++。几天以来尝试了很多将其转换为JAVA,无法想出办法:
下面的 C++ 代码行
map<Character,Integer> enc = new map<Character,Integer>();
注意:将上面的语法改为HashMap/Map,并导入Java.Util后,下面代码中标有3星的代码行显示以下错误“表达式的类型必须是数组类型,但已解析为Map”
1) enc[input.charAt(i)] = i; 2) int pos = enc[msg.charAt(i) - 32]; 3) int pos = enc[msg.charAt(i)];
// 此函数将解密任何输入消息
public static String ABC(String msg, String input)
{
// Hold the position of every character (A-Z) from encoded string
map<Character,Integer> enc = new map<Character,Integer>();
for (int i = 0; i < input.length(); i++)
{
***enc[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[msg.charAt(i) - 32];***
decipher += plaintext.charAt(pos);
}
else if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z')
{
***int pos = enc[msg.charAt(i)];***
decipher += plaintext.charAt(pos);
}
else
{
decipher += msg.charAt(i);
}
}
return decipher;
}
map<Character,Integer> enc = new map<Character,Integer>();
Map
是 Java 中的接口类型,不能实例化 [作为匿名内部类以外的任何东西]。您需要实例化实现 的类型之一Map
,例如TreeMap
或HashMap
。
//Since Java 7, <> infers the type arguments
Map<Character, Integer> enc = new HashMap<>();
enc[input.charAt(i)] = i;
您使用的方括号运算符 ( enc[input.charAt(i)]
) 是 C++ 原生的,在 Java 中不可重载;因此,Java 中唯一允许使用这些类型的括号是在使用数组时。
您需要使用get()
和put()
与Java 地图。
enc.put(input.charAt(i), i);
//...
int pos = enc.get(msg.charAt(i) - 32);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句