4

编程语言:Java 任务:设计一个将中文字符串映射到数字的哈希函数问题:正确阅读和显示汉字

这是一道作业题,但我不是在问怎么做,只是在阅读汉字时遇到了困难。

我的任务的简短描述:设计一个散列函数,将我们班的(中国)学生姓名映射到他们的学生 ID 和其他卫星数据(性别、电话等)。

我仍在考虑它,但就像其他语言一样,这涉及到我使用字符的字符编码来通过哈希函数得出一个唯一值,如果我没记错的话。

以下是我必须测试这种思路的有效性的内容:

// test whether console can read chinese characters
Scanner s = new Scanner(System.in);

System.out.print("Please enter a Chinese character: ");
int chi = (int)s.next().toCharArray()[0];

System.out.println("\nThe string entered is " + chi);

如果我使用简单的 System.out.println("character") 语句,则会显示正确的字符。

但如上所示,如果我使用 Scanner 读取输入,我尝试将 String 转换为 char 数组,然后转换为它的 int unicode 等价物,但它给出了一个荒谬的数字,我无法正确显示它。

我意识到我可以使用这个错误值来设计一个哈希函数,但是为了不产生可能的冲突(我不知道这些是否会产生 UNIQUE 错误值),并且为了学习,你能指出如何我可以在不同的机器上统一输入汉字吗?

永远感谢你的想法。:D

巴乔。

4

3 回答 3

3

创建 Scanner 时,您还可以告诉它使用哪种字符编码。这是文档。

于 2012-10-15T14:52:08.033 回答
3

当您不使用基本的 ASCII 字符时,您需要考虑您使用的是哪个字符集。大多数情况下它将是 UTF-8,但也可以使用其他字符集。

要记住的一件事是非 ASCII 字符的大小可以超过 1 个字节。汉字也是如此。

处理多字节字符时,您需要考虑代码点(表示 UTF-8 字符的整数)而不是单字节字符。

较新版本的 Java 允许您使用代码点迭代字符串。查看 String 的 Java API。

于 2012-10-15T15:13:48.657 回答
1

You are over-thinking this. Every String is already (conceptually) a sequence of characters, including Chinese characters.. Encoding only comes into it when you need to convert it into a bytes, which you don't need to for your assignment. Just use the String's hashcode. In fact, when you create a HashMap<String,YourObject>, that's exactly what will happen behind the scenes.

于 2012-10-15T15:46:14.160 回答