Results 1 to 4 of 4
- 02-09-2010, 01:44 AM #1
Member
- Join Date
- Feb 2010
- Posts
- 3
- Rep Power
- 0
Java class HashIt with a static recursive method and a static iterative method
hi, i could use some help with this problem: Write a Java class HashIt with a static recursive method and a static iterative (using while- or
for-loop) method to compute the hash function ∑ ASCII-value(ai) mod 50, i=1 to n. Be sure to include the main method and test cases. This is what i've got so far, but not getting the correct ascii values...
public class HashItTestCases
{
public static void main (String[] args)
{
HashIt hashtest1 = new HashIt ();
HashIt hashtest2 = new HashIt ();
String string = "abc";
hashtest1.hashItR(string);
hashtest2.hashItI(string);
System.out.println(hashtest1);
System.out.println(hashtest2);
}
}
//
class HashIt
{
//private static char firstChar;
//private static String restStr;
// static recursive method
public static int hashItR(String s)
{
char firstChar;
String restStr;
if( s.length()== 0)
return 0 ;
else
{ firstChar = s.charAt(0);
restStr = s.substring(1, s.length());
return ( ((int) firstChar + hashItR(restStr)) % 50 );
}
}
// tail recursive method
public static int hashItI(String s)
{
int asciiVal = 0;
int count = 0;
if (s.length() == 0)
return 0;
else
while (count < s.length())
{
asciiVal = ((int) s.charAt(count)) + asciiVal;
count++;
}
return asciiVal % 50;
}
}
output:
HashIt@1fb8ee3
HashIt@61de33
- 02-09-2010, 02:18 AM #2
Senior Member
- Join Date
- Nov 2009
- Posts
- 236
- Rep Power
- 12
You are printing out the object, not the hash. You need to make a method in HashIt called toString() and have it return the hash value.
- 02-09-2010, 02:22 AM #3
Senior Member
- Join Date
- Nov 2009
- Posts
- 236
- Rep Power
- 12
Oh, just noticed your methods are static, therefore, there is no need to even create hashtest1 and hashtest2, just say:
System.out.println(HashIt.hashItR("abc"));
System.out.println(HashIt.hashItI("abc"));
In the main method. I got
44
44
- 02-09-2010, 05:22 AM #4
Member
- Join Date
- Feb 2010
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
non-static method cannot be referenced from a static context.
By blackstormattack in forum New To JavaReplies: 5Last Post: 05-07-2009, 04:05 AM -
make static ref to non-static method?
By McChill in forum New To JavaReplies: 7Last Post: 02-23-2009, 05:48 AM -
static method sparks error on overriding non-static method
By MuslimCoder in forum New To JavaReplies: 1Last Post: 02-10-2009, 10:03 AM -
Non-Static method in static context error
By wizmang in forum New To JavaReplies: 4Last Post: 04-24-2008, 08:51 AM -
Error: Non-static method append(char) cannot be referenced from a static context
By paul in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 05:05 AM
Bookmarks