user8414403
user8414403

Reputation:

Hash Table Java

I have provided a simple hash table program. However, the output is outputting non-needed zeros. I have searched on a solution to exclude the zeros. Any suggestions on how? The output is provided below the program.

import java.util.Random;

class HashTable
{
int[] arr;
int c;

public HashTable(int capacity)
    {
    this.c = nextPrime(capacity);
    arr = new int[this.c];
    }


public void insert(int ele)
{
    arr[ele % c] = ele;
}

public void clear()
{
    arr = new int[c];
}

public boolean contains(int ele)
{
    return arr[ele % c] == ele;
}

private static int nextPrime( int n )
{
    if (n % 2 == 0)
        n++;
    for (; !isPrime(n); n += 2);

    return n;
}

private static boolean isPrime(int n)
{
    if (n == 2 || n == 3)
        return true;
    if (n == 1 || n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}
public void printTable()
{
    System.out.print("Hash Table:\n ");
    for (int i = 0; i < c; i++)
        System.out.print(arr[i] +" ");
    System.out.println();
}
}


 public class HashTableTest
{
public static void main(String[] args)
{
    int j;
    for(j = 0; j <= 5; j++)
    {
        Random random = new Random();
        int range = 100 - 25 + 1;
        int rm = random.nextInt(range) + 25;
        HashTable ht = new HashTable(rm);

   int i;
        for(i = 0; i <= rm ; i++)
        {
            Random ran = new Random();
            int rn = 20000 - 1 + 1;
            int m = ran.nextInt(rn);
            ht.insert(m);

        }

    ht.printTable();  
    }                
}   
}

Output:

Hash Table:
 5162 19492 0 0 0 18695 0 15582 19499 17542 13271 2948 3839 17457 15411 
13810 15769 0 0 0 10344 15062 0 0 11416 11595 17826 0 4389 8929 0 0 19434 0 
0 16767 9025 0 6891 11164 15437 19176 0 399 0 15086 11349 0 19628 227 17939 
 0 5214 18565 7441 19635 0 0 15633 0 0 0 5313 15905 11011 4604 0 0 3450 0 0 
12709 0 6659 9597 12535 19923 18589 11203 16010 13430 5688 5155 11742 0 
10142 5070 16552 4271 

I know that it loops and provides Five different hash tables but that would be very long and unnecessary for this post.

Upvotes: 0

Views: 203

Answers (1)

elp
elp

Reputation: 870

If you just want to exclude the 0's from the outprint this could solve the issue. Your for-loop would look like:

for (int i = 0; i < c; i++){
    if(arr[i]!=0){
        System.out.print(arr[i] +" ");
    }
}

Upvotes: 1

Related Questions