我试图在java中创建一个半效率的哈希表,并最终在无限循环中结束

时间:2015-09-30 06:52:29

标签: java hash infinite-loop

我现在一直默默地盯着这件事,我只是没有看到我的错误......如果有人能指出我正确的方向,我将非常感激。谢谢!

公共课堂学习哈希{

public static void main(String[] args)  throws IOException
{
    java.io.File file = new java.io.File(args[0]); //Read the data from the file
    Scanner input = new Scanner(file);
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++
    int max = 13; // array size
    int j = 0;                          // index for hash keys
    String[] mainData = new String[max];     // items array
    String[] inputData = new String[max];   // temp array
    int in = 0;                              // needed variables

    long temp;
    int loc;
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++

        while (input.hasNextLine()) {  // read file until none left

            inputData[in] = String.valueOf(input.hasNextLine());

            String[] breaks =  inputData[in].split(" "); // checks for space and splits

            if(breaks.length == 2) // if equal 2 store i.e "eco 32" will become "eco" and "32" therefore ==2
            {
               temp = hashing(breaks[0], max); // creating a hash key
                loc = (int)temp; // converting from long to int

                if(mainData[loc] != null)
                {
                    while(mainData[loc] != null)
                    {
                        System.out.println("Collision at [" + loc + "] with Data Item : [" + mainData[loc] + "] ");
                        loc++;
                        if(loc > max)
                        {
                            loc = 0;
                        }
                    }
                }
                mainData[loc] = (breaks[0]+" "+breaks[1]); // recombines i.e "moss space 25" and stores it in data location
                System.out.println("Data Item[" + mainData[loc] + "] Stored in index [" + loc + "] of array.");
            }
            else // i.e "eco' without "32" belongs into this criteria
            {
                temp = hashing(breaks[0], max); // creating a hash key
                loc = (int)temp; // converting from long to int               
                while((mainData[loc] != breaks[0]) && (mainData[loc] != null) )
                {
                    loc++;
                    if(loc > max)
                        loc = 0;
                }
                if(mainData[loc] == null)
                {System.out.println("ERROR Data item ["+ breaks[0] + "] was NOT found. ");}
                else
                {
                    System.out.println(" Data item [" + breaks[0]+ "] was found at location ["+ loc+"] .");
                }
            }
     }
    input.close();
}

1 个答案:

答案 0 :(得分:1)

我想这个:

inputData[in] = String.valueOf(input.hasNextLine());

应替换为

inputData[in] = String.valueOf(input.nextLine());

然后你会读出数据而不仅仅询问下一行是否可用并读出布尔值......我认为这会产生一个无限循环;)