1

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);
10
  • What is not working? Commented Oct 24, 2016 at 20:37
  • What isn't working? What output are your expecting and what are you getting? What is the exact error message you see? Commented Oct 24, 2016 at 20:37
  • I'm expecting an integer output of some sort depending on whatever the string input is. Commented Oct 24, 2016 at 20:37
  • 1
    If you are expecting an integer, why is hashValue of type String? Commented Oct 24, 2016 at 20:39
  • 1
    Remove the unnecessary assignment here String hashValue = inStr; and instead just do int hashValue = inStr.hashCode() Commented Oct 24, 2016 at 20:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.