Dan
Dan

Reputation: 43

Returning after a for loop

I need to create my own HashCode() method which computes the HashCode of a String.

My code looks like this so far

    public long HashCode(String n){
        long x = 0;
        for(int i=0; i >= n.length()-1; i++){
            x =+ 31^(n.length() -1) * n.charAt(i);
        }
        System.out.println(Long.toString(x));
        return x;
    }

My println prints "0" although it has been altered inside the for loop. Is there any way to return the changed x, rather than the initialized x=0?

Upvotes: 0

Views: 64

Answers (5)

Suresh Atta
Suresh Atta

Reputation: 121998

Condition should be <= not >=

for (int i = 0; i <= n.length() - 1; i++) {
        x = +31 ^ (n.length() - 1) * n.charAt(i);
    }

More over

for (int i = 0; i < n.length(); i++) {
            x = +31 ^ (n.length() - 1) * n.charAt(i);
        }

Is enough.

And as per you comment , "Cat" which should return 67510, Your logic needs to be change.

Check here, For "Cat" as a input, Your code producing 247

Upvotes: 1

Mostafa Jamareh
Mostafa Jamareh

Reputation: 1439

change your code like this

        long x = 0;
    for (int i = 0; i <= n.length() - 1; i++) {
        x += 31 ^ (n.length() - 1) * n.charAt(i);
    }
    System.out.println(Long.toString(x));

your condition was wrong , try debuging your code to find out what the problem is

Upvotes: 0

Coder
Coder

Reputation: 7076

Shouldn't it be

for(int i=0; i <= n.length()-1; i++){  
      //OR
for(int i=0; i < n.length(); i++){ 

Instead of

for(int i=0; i >= n.length()-1; i++){

?

Upvotes: 0

jdigital
jdigital

Reputation: 12266

In addition to the other corrections, it looks like you meant to use the += but instead your code says = +

x =+ 31^(n.length() -1) * n.charAt(i);

should be

x += 31^(n.length() -1) * n.charAt(i);

Upvotes: 0

TheKojuEffect
TheKojuEffect

Reputation: 21081

i = 0;  and i >= n.length()-1;

then for loop is never executed.

Instead use

for(int i=0; i < n.length(); i++)

Upvotes: 4

Related Questions