我正在寻求帮助创建一个哈希函数,该函数将从字符串输入的用户数据并将其转换为整数值,同时跳过空格。我很困惑为什么它不起作用,以及如何让它获得可以输入的空白,并希望得到帮助。
代码:
public static void main(String[] args) {
Scanner inScan;
String inStr;
int outHash;
inScan = new Scanner(System.in); // Assignment of Scanner
System.out.print("Enter string to create hash: "); // Asks for String Input
inStr = inScan.nextLine(); // String Input
// Start of Hash Function
String hashValue = inStr;
hashValue = inStr.hashCode();
System.out.println(hashValue);
最佳答案
您的代码调用hashCode()
不变inStr
。您应该清除 inStr
中的空格在调用hashCode
之前确保仅空格不同的字符串的哈希码相同:
String a = "a bc";
String b = "ab c";
String c = "a b c";
int hashA = a.<remove-white-space>.hashCode();
int hashB = b.<remove-white-space>.hashCode();
int hashC = c.<remove-white-space>.hashCode();
<remove-white-space>
是你需要写的东西。咨询this Q&A寻求有关此任务的帮助。
如果您正确完成任务,hashA
, hashB
,和hashC
彼此相等。
关于Java:哈希函数输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40227084/