【发布时间】:2017-06-16 10:08:14
【问题描述】:
我正在尝试存储字母到二进制数的映射。这是我的映射
("h",001)
("i", 010)
("k",011)
("l",100)
("r", 101)
("s",110)
("t",111)
为此,我创建了一个哈希映射并存储了键值对。我现在想为给定的句子显示相应的二进制值。这是我的代码。
package crups;
import java.util.*;
public class onetimepad {
public static void main(String args[])
{
HashMap <String , Integer>hm = new HashMap <String , Integer> ();
hm.put("e", 000);
hm.put("h",001);
hm.put("i", 010);
hm.put("k",011);
hm.put("l",100);
hm.put("r", 101);
hm.put("s",110);
hm.put("t",111);
String[] key = { "t" ,"r" , "s" , "r","t","l","e", "r","s","e"};
//key = t r s r t l e r s e
String[] input = {"h","e","i" ,"l","h","i","t","l","e","r"};
int[] cipher = new int[10];
System.out.println("Binary form of text is ....");
for( String s : input )
{
System.out.print(hm.get(s)+" ");
}
}
}
但是,当我运行代码时,字母“i”的映射显示错误:8:而不是010。
有人可以告诉我为什么会这样吗?另外,我如何在我的数字前面显示零,因为这些是二进制数。
谢谢。
输出:
Binary form of text is ....
1 0 8 100 1 8 111 100 0 101
【问题讨论】:
-
将它们存储为字符串 ("001") 而不是数字。
-
这也是一些有趣的输入文本。
-
@LukeBriggs:哈哈,这显然是一个很容易形成不同句子的文本,通过排列。
-
您在源代码中查看的数字是十进制的 - 例如,
101是“一百零一”。你会选择代表你想要的二进制的十进制数字。 (例如十进制的4是二进制的100),然后使用converting an int to a binary string 之类的东西来方便地显示位:) -
@shmosel 将它们存储为字符串 ("001") 而不是数字。 现在谁在作弊?