简体   繁体   中英

Error: Array index out of bound Java

It compiles but gives an error of Array IndexOutOfBoundsException : -104421 whenever executed with files provided

/* HashTable.java
  Template for a hash table with String elements.

   You should complete this file with the implementation for part 3.

   This template includes some testing code to help verify the implementation.
   To interactively provide test inputs, run the program with
    java HashTable3

   Input data should consist of a list of strings to insert into the hash table, one per line,
   followed by the token "###" on a line by itself, followed by a list of strings to search for,
   one per line.

   To conveniently test the algorithm with a large input, create
   a text file containing the input data and run the program with
    java HashTable3 file.txt
   where file.txt is replaced by the name of the text file.
*/

import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.io.File;


public class HashTable3{


    /* **************** HASH TABLE METHODS **************** */

    //The size of the hash table.`enter code here`
    //Do not change this value.
    public static final int TableSize = 225225;

    //The TableStorage object T represents the array used for the table.
    //To retrieve the element at index i, use the method T.getElement(i).
    //To set the element at index i to a value s, use the method T.setElement(i,s).
    //You must use only the object below to access the table values.
    //If you access the table by any other means, or use a different data structure
    //to represent the table, your submission will not be marked.
    TableStorage T = new TableStorage(TableSize);

    /* hash(s)
       Return the hash code for the provided string.
       The returned value must be in the range [0,TableSize-1]
    */
    public int hash(String s){
        int i;
        long location = 0;
        int val;
        for(i = 0; i< s.length(); i++){
            val = s.charAt(i);
            location = location + ((int)Math.pow(2, i)*(val));
            if(location < 0){
                location *= (-1);
            }
        }
        location = location % TableSize;
        return (int)location;
    }

    /* insert(s)
       Insert the value s into the hash table and return the index at
       which it was stored.
    */
    public int insert(String s){

        //Get the hash value of the string and start the search at that index.
        int i = hash(s);
        int k = 0;
        int j = 1;
        long hash2 = 1;
        int val1;
        for(k = 0 ; k< s.length(); k++){
            val1 = s.charAt(k);
            hash2 = hash2 + ((int)Math.pow(3, k)*(val1));
            if(hash2 < 0){
                hash2 *= (-1);
            }
        }
        //Use linear probing to find an empty slot.
        while(T.getElement(i) != null){
            i = i + j*(int)hash2;
            if (i >= TableSize)
                i = i%TableSize;
            j++;
        }
        T.setElement(i,s);
        return i;
    }

    /* find(s)
       Search for the string s in the hash table. If s is found, return
       the index at which it was found. If s is not found, return -1.
    */
    public int find(String s){

        //Get the hash value of the string and start the search at that index.
        int i = hash(s);
        int k;
        int j = 1;
        long hash3 = 1;
        int val2;
        for(k = 0; k< s.length(); k++){
            val2 = s.charAt(k);
            hash3 = hash3 + ((int)Math.pow(3, k)*(val2));
            if(hash3 < 0){
                hash3 *= (-1);
            }
        }
        //Use linear probing to find the string.
        while (true){
            String element = T.getElement(i);
            //If the slot is empty, the provided string was not found.
            if (element == null)
                return -1;
            //If the slot contains the desired string, return its index.
            //Note that to test whether strings are equal in Java,
            //the '==' operator is not correct.
            if (s.equals(element))
                return i;
            //If the string was not at this index, continue looking.
            i = i + j*(int)hash3;
            j++;
            if (i >= TableSize)
                i = i%TableSize;
        }
    }

    /* **************************************************** */




    /* **************** TableStorage Class **************** */
    /* The hash table methods use this class to store
       and retrieve table values. Do not modify this class in
       any way. If this class is modified, it may not be possible
       to mark your submission.
    */
    public static class TableStorage{

        public TableStorage(int tableSize){
            table = new String[tableSize];
            resetProbeCount();
        }
        private String[] table;
        private long probeCount,lastProbed;
        public void resetProbeCount() { probeCount = 0; lastProbed = -1; }
        public long getProbeCount() { return probeCount; }

        public void setElement(int index, String value){
            table[index] = value;
        }
        public String getElement(int index){
            if (index != lastProbed)
                probeCount++;
            lastProbed = index;
            return table[index];
        }
    }
    /* **************************************************** */

    /* main()
       Contains code to test the hash table methods. Nothing in this function
       will be marked. You are free to change the provided code to test your
       implementation, but only methods above will be considered for marking.
    */
    public static void main(String[] args){
        Scanner s;
        boolean interactiveMode = false;
        if (args.length > 0){
            try{
                s = new Scanner(new File(args[0]));
            } catch(java.io.FileNotFoundException e){
                System.out.printf("Unable to open %s\n",args[0]);
                return;
            }
            System.out.printf("Reading input values from %s.\n",args[0]);
        }else{
            interactiveMode = true;
            s = new Scanner(System.in);
        }
        s.useDelimiter("\n");
        if (interactiveMode){
            System.out.printf("Enter a list of strings to store in the hash table, one per line.\n");
            System.out.printf("To end the list, enter '###'.\n");
        }else{
            System.out.printf("Reading table values from %s.\n",args[0]);
        }

        Vector<String> tableValues = new Vector<String>();
        Vector<String> searchValues = new Vector<String>();
        String nextWord;

        while(s.hasNext() && !(nextWord = s.next().trim()).equals("###"))
            tableValues.add(nextWord);
        System.out.printf("Read %d strings.\n",tableValues.size());

        if (interactiveMode){
            System.out.printf("Enter a list of strings to search for in the hash table, one per line.\n");
            System.out.printf("To end the list, enter '###'.\n");
        }else{
            System.out.printf("Reading search values from %s.\n",args[0]);
        }

        while(s.hasNext() && !(nextWord = s.next().trim()).equals("###"))
            searchValues.add(nextWord);
        System.out.printf("Read %d strings.\n",searchValues.size());

        HashTable3 H = new HashTable3();
        long startTime, endTime;
        double totalTimeSeconds;
        long totalProbes = 0;
        long maxProbes = 0;

        totalProbes = 0;
        maxProbes = 0;
        startTime = System.currentTimeMillis();

        for(int i = 0; i < tableValues.size(); i++){
            H.T.resetProbeCount();
            String tableElement = tableValues.get(i);
            long index = H.insert(tableElement);
            long probeCount = H.T.getProbeCount();
            String insertedElement = (index >= 0)? H.T.getElement((int)index): null;
            if (insertedElement != null && !insertedElement.equals(tableElement))
                System.out.printf("Inserting \"%s\": Returned value does not match value inserted.\n",tableElement);
            if (probeCount > maxProbes)
                maxProbes = probeCount;
            totalProbes += probeCount;
        }
        endTime = System.currentTimeMillis();
        totalTimeSeconds = (endTime-startTime)/1000.0;

        System.out.printf("Inserted %d elements.\n Total Time (seconds): %.2f\n Total Probes: %d\n Max. Probes: %d\n",tableValues.size(),totalTimeSeconds, totalProbes, maxProbes);

        totalProbes = 0;
        maxProbes = 0;
        int foundCount = 0;
        int notFoundCount = 0;
        startTime = System.currentTimeMillis();

        for(int i = 0; i < searchValues.size(); i++){
            H.T.resetProbeCount();
            String searchElement = searchValues.get(i);
            long index = H.find(searchElement);
            long probeCount = H.T.getProbeCount();
            String foundElement = (index >= 0)? H.T.getElement((int)index): null;
            if (foundElement == null)
                notFoundCount++;
            else
                foundCount++;
            if (foundElement != null && !foundElement.equals(searchElement))
                System.out.printf("Search for \"%s\": Returned value does not match search string.\n",searchElement);
            if (probeCount > maxProbes)
                maxProbes = probeCount;
            totalProbes += probeCount;
        }
        endTime = System.currentTimeMillis();
        totalTimeSeconds = (endTime-startTime)/1000.0;

        System.out.printf("Searched for %d items (%d found, %d not found).\n Total Time (seconds): %.2f\n Total Probes: %d\n Max. Probes: %d\n",
                            searchValues.size(),foundCount,notFoundCount,totalTimeSeconds, totalProbes, maxProbes);
    }
}

While your hash() function is protected from returning a negative value (because of the location = location % TableSize; which keeps it in the range between zero and TableSize before it converts to integer), there is no such protection for your second hashing operation:

    for(k = 0 ; k< s.length(); k++){
        val1 = s.charAt(k);
        hash2 = hash2 + ((int)Math.pow(3, k)*(val1));
        if(hash2 < 0){
            hash2 *= (-1);
        }
    }

This loop makes certain that a positive long is returned. That is, if you had an overflow from the pow operation (which, by the way, should have been cast to long rather than int , in the hash() function as well), then the hash2 *= (-1) would make it positive.

But... inside your while loop, you are doing:

        i = i + j*(int)hash2;

And here, hash2 is converted from long to int without protection. A conversion from long to int simply takes the least significant 32 bits of the 64 bits of the long . If the leftmost bit of this number is set, you'll get a negative integer. Try this:

    long l = 59827492823954687L;
    int i = (int)l;
    System.out.println(i);

You should protect the value while it is still long, like you did in the actual hash() , or add another condition:

    if ( i < 0 ) {
        i = -i;
    }

Just before your if (i >= TableSize) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM