Create a class called StringHashCode which besides a main method provides the fo
ID: 3692655 • Letter: C
Question
Create a class called StringHashCode which besides a main method provides the following method: public static int strHashCode(String str) This method should return the integer hash code of the string parameter str using the formula given below: Hashcode = str[0]*31^(n-1) + str[1]*31^(n-2) + ... + str[n-2] *31^(1) + str[n-1] Here str[0] means the first character in str and str[1] means second character of str and so on. With n we denote the length of the string str, * means multiplication and ^ represents the power (exponent). For example if str = “abc”, then we have: hashcode = ‘a’*31^2 + ‘b’*31^1 + ‘c’ Note: Using some character such as ‘b’ in arithmetic calculations automatically replaces it with its ASCII code. That is, you don’t need to worry about it, java will handle it automatically. In the main method of your class, write code to ask the user to enter a string, then pass this string input to the method strHashCode and print the hash code returned by the method on the monitor screen. Then, your program should print to the user: Do you want to enter a new string (Y/N). Based on the use choice, program should proceed.
Explanation / Answer
Hello there ,
Please find below code and it's O/P.
import java.util.Scanner;
/**
* The Main driver program to calculate String hash code based on the given
* function.
*
* @author dipal.prajapati
*
*/
public class StringHashCode {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter String to calculate hash : ");
String str = scanner.next();
System.out.println("HashCode for ""+str+"" is "+ getHashCode(str));
while (true) {
System.out.println("Do you want to enter a new string (Y/N): ");
if (scanner.next().toLowerCase().equals("y")) {
System.out.println("Enter String to calculate hash : ");
str = scanner.next();
System.out.println("HashCode for " "+str+"" is "+ getHashCode(str));
} else {
break;
}
}
}
/**
* It calculates hash for the given string.
* @param str
* @return
*/
public static int getHashCode(String str) {
int hashCode = 0;
for (int i = 0; i < str.length(); i++) {
hashCode = hashCode + str.charAt(i) * 31 ^ (str.length() - (i + 1));
}
return hashCode;
}
}
======O/P======
Enter String to calculate hash :
John
HashCode for "John" is 12367
Do you want to enter a new string (Y/N):
Y
Enter String to calculate hash :
Jinal
HashCode for " Jinal" is 15312
Do you want to enter a new string (Y/N):
y
Enter String to calculate hash :
Meha
HashCode for " Meha" is 11743
Do you want to enter a new string (Y/N):
N
Let me know if you have any doubts.
Thanks.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.