Aramza
Aramza

Reputation: 193

Java: Hash Function Inputted Strings

I am seeking help creating a hash function that will take user data inputted from a string and convert it into an integer value, all the while skipping white spaces. I am stumped on why it's not working, and how to get it to get white spaces that may be entered and would appreciate the help.

Code:

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);

Upvotes: 1

Views: 708

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

Your code calls hashCode() on unchanged inStr. You should clear out whitespace from inStr before calling hashCode to make sure hash codes of strings that differ only in white space are identical:

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> is something you need to write. Consult this Q&A for help on this task.

If you do your task correctly, hashA, hashB, and hashC would be equal to each other.

Upvotes: 1

Related Questions