首页 \ 问答 \ Java HashTable实现get方法返回null?(Java HashTable Implementation get method returning null?)

Java HashTable实现get方法返回null?(Java HashTable Implementation get method returning null?)

所以我需要编写这个程序,收到包含NFL球队名称和分数的17个文件(比如一个文件包含所有32支球队的得分,而另一个文件可能包含30个不同的得分,但是30个相同的球队,但当然省略了两个球队)。 我的教授为我们提供了一个HashTable实现,它通过在HashTable中的每个占用索引上创建某种LinkedList来处理冲突(我相当缺乏经验,所以如果我没有得到全部的话,我很抱歉术语正确,但希望你知道我的意思)。 我已经成功导入了所有文件和数据,并通过我教授给我们的碰撞处理将它们输入到HashTable中。 但是,每当我尝试为任何键调用get方法时,它都会返回“null”。 为什么是这样? 我问,因为我需要找到每个团队的平均团队得分,而我无法想出这样做,因为get方法返回null。 任何帮助将非常感激!

码:

HashEntry:

public class HashEntry 
{
private String key;
private Double value;
private HashEntry next;

public HashEntry(String key, Double value) 
{
    this.key = key;
    this.value = value;
}

public String getKey() 
{
    return key;
}

public void setKey(String key) 
{
    this.key = key;
}

public Double getValue() 
{
    return value;
}

public void setValue(Double value) 
{
    this.value = value;
}

public HashEntry getNext() 
{
    return next;
}

public void setNext(HashEntry next) 
{
    this.next = next;
}

public boolean isNextEmpty()
{
    if(next.equals(null))
        return true;
    return false;
}

哈希表:

public class HashTable implements StringHashTable 
{
private HashEntry[] dataArray;
private int size;

public HashTable() 
{
    dataArray = new HashEntry[1000];
    size = 0;
}

private int hash(String key) 
{
    int sum = 0;
    for(int i = 0; i < key.length(); i++)
        sum += (int)key.charAt(i);

    return sum % dataArray.length;
}

@Override
public void put(String key, Double value) 
{
    HashEntry entry = new HashEntry(key, value);
    int indexToPut = hash(key);
    HashEntry cursor = dataArray[indexToPut];
    if(cursor != null) 
    {
        while(cursor.getNext() != null && cursor.getKey() != key) 
        {
            cursor = cursor.getNext();
        }
        if(cursor.getKey() != key) 
        {
            cursor.setNext(entry);
        } 
        else 
        {
            cursor.setValue(value);
        }
    } 
    else 
    {
        dataArray[indexToPut] = entry;
    }
    size++;
}

@Override
public Double get(String key) 
{
    int indexToGet = hash(key);
    HashEntry cursor = dataArray[indexToGet];
    while(cursor != null && cursor.getKey() != key) 
    {
        cursor = cursor.getNext();
    }
    if (cursor == null) 
    {
        return null;
    }
    return cursor.getValue();
}

@Override
public int size() 
{
    return size;
}

@Override
public void remove(String key) 
{
    int indexToRemove = hash(key);
    HashEntry cursor = dataArray[indexToRemove];
    HashEntry prev = null;
    while(cursor != null && cursor.getKey() != key) 
    {
        prev = cursor;
        cursor = cursor.getNext();
    }
    if (cursor != null) 
    {
        if (prev == null) 
        {
            dataArray[indexToRemove] = cursor.getNext();
        } 
        else 
        {
            prev.setNext(cursor.getNext());
        }
        size--;
    }
}

public String toString() 
{
    String res = "";
    for(HashEntry entry : dataArray) 
    {
        if (entry != null) 
        {
            HashEntry cursor = entry;
            while(cursor != null) 
            {
                res += cursor.getKey() + " = " + cursor.getValue() + "\n";
                cursor = cursor.getNext();
            }
        }
    }
    return res;
}

驾驶员类:

public class Project3 
{
static HashTable table = new HashTable();   
static HashMap<String, Double> table1 = new HashMap<String, Double>();
public static void main(String[] args) throws IOException
{
    //HashTableImpl<String, Double> table = new HashTableImpl<String, Double>();

    if (args.length < 1) 
    {
        System.out.println("Error: Directory name is missing");
        System.out.println("Usage: java scoreProcess directory_name");
        return;
    }

    File directory = new File(args[0]); // args[0] contains the directory name
    File[] files = directory.listFiles(); // get the list of files from that directory

    File file;
    Scanner input;

    // process the arguments stores in args
    for (int i = 0; i < files.length; i++) 
    {
        input = new Scanner(files[i]);

        //System.out.println("\nCurrent file name: " + files[i].getName());

        // no error checking done here, add your own
        String name;
        Double score;
        while(input.hasNext())
        {
            name = "";
            while(!input.hasNextDouble())
            {
                name += input.next() + " ";
            }
            score = input.nextDouble();
            //System.out.println("Name: " + name + " Score: " + score);
            table.put(name, score);
            table1.put(name, score);
        }
    }
    System.out.println("\n");
    System.out.println(table.toString());
    System.out.println(table.size());
    //System.out.println(table1.toString());
    System.out.println(table.get("Minnesota"));
}
}

驱动程序输出: https //drive.google.com/file/d/0BwujWiqVRKKsNW52N1M2UllCeHc/view?usp=sharing

示例文本文件:

New England 27
Indianapolis 24
Tennessee 17
Miami 7
St. Louis 17
Arizona 10
Seattle 21
New Orleans 7
NY Jets 31
Cincinnati 24
Pittsburgh 24
Oakland 21
Washington 16
Tampa Bay 10
San Diego 27
Houston 20
Jacksonville 13
Buffalo 10
Detroit 20
Chicago 16
Cleveland 20
Baltimore 3
Atlanta 21
San Francisco 19
Philadelphia 31
NY Giants 17
Minnesota 35
Dallas 17
Denver 34
Kansas City 24
Green Bay 24
Carolina 14

So I need to write this program that receives 17 files that contain NFL team names and scores (like one file contains scores for all 32 teams, while another file may contain 30 different scores for 30 of the same teams, but omitting two teams of course). And my professor provided us with a HashTable implementation to use, and it handles the collisions by creating some sort of LinkedList at each occupied index in the HashTable (I'm fairly inexperienced, so I'm sorry if I don't get the all the terminology correct, but hopefully you know what I mean). I have successfully imported all the files and data and have inputted them into the HashTable with the collision handling that my professor gave us. However, whenever I try to call the get method for any of the keys, it returns "null". Why is this? I ask because I need to find the average team score for each team, and I can't figure out to do this because the get method is returning null. Any help would be much appreciated!

Code:

HashEntry:

public class HashEntry 
{
private String key;
private Double value;
private HashEntry next;

public HashEntry(String key, Double value) 
{
    this.key = key;
    this.value = value;
}

public String getKey() 
{
    return key;
}

public void setKey(String key) 
{
    this.key = key;
}

public Double getValue() 
{
    return value;
}

public void setValue(Double value) 
{
    this.value = value;
}

public HashEntry getNext() 
{
    return next;
}

public void setNext(HashEntry next) 
{
    this.next = next;
}

public boolean isNextEmpty()
{
    if(next.equals(null))
        return true;
    return false;
}

HashTable:

public class HashTable implements StringHashTable 
{
private HashEntry[] dataArray;
private int size;

public HashTable() 
{
    dataArray = new HashEntry[1000];
    size = 0;
}

private int hash(String key) 
{
    int sum = 0;
    for(int i = 0; i < key.length(); i++)
        sum += (int)key.charAt(i);

    return sum % dataArray.length;
}

@Override
public void put(String key, Double value) 
{
    HashEntry entry = new HashEntry(key, value);
    int indexToPut = hash(key);
    HashEntry cursor = dataArray[indexToPut];
    if(cursor != null) 
    {
        while(cursor.getNext() != null && cursor.getKey() != key) 
        {
            cursor = cursor.getNext();
        }
        if(cursor.getKey() != key) 
        {
            cursor.setNext(entry);
        } 
        else 
        {
            cursor.setValue(value);
        }
    } 
    else 
    {
        dataArray[indexToPut] = entry;
    }
    size++;
}

@Override
public Double get(String key) 
{
    int indexToGet = hash(key);
    HashEntry cursor = dataArray[indexToGet];
    while(cursor != null && cursor.getKey() != key) 
    {
        cursor = cursor.getNext();
    }
    if (cursor == null) 
    {
        return null;
    }
    return cursor.getValue();
}

@Override
public int size() 
{
    return size;
}

@Override
public void remove(String key) 
{
    int indexToRemove = hash(key);
    HashEntry cursor = dataArray[indexToRemove];
    HashEntry prev = null;
    while(cursor != null && cursor.getKey() != key) 
    {
        prev = cursor;
        cursor = cursor.getNext();
    }
    if (cursor != null) 
    {
        if (prev == null) 
        {
            dataArray[indexToRemove] = cursor.getNext();
        } 
        else 
        {
            prev.setNext(cursor.getNext());
        }
        size--;
    }
}

public String toString() 
{
    String res = "";
    for(HashEntry entry : dataArray) 
    {
        if (entry != null) 
        {
            HashEntry cursor = entry;
            while(cursor != null) 
            {
                res += cursor.getKey() + " = " + cursor.getValue() + "\n";
                cursor = cursor.getNext();
            }
        }
    }
    return res;
}

Driver Class:

public class Project3 
{
static HashTable table = new HashTable();   
static HashMap<String, Double> table1 = new HashMap<String, Double>();
public static void main(String[] args) throws IOException
{
    //HashTableImpl<String, Double> table = new HashTableImpl<String, Double>();

    if (args.length < 1) 
    {
        System.out.println("Error: Directory name is missing");
        System.out.println("Usage: java scoreProcess directory_name");
        return;
    }

    File directory = new File(args[0]); // args[0] contains the directory name
    File[] files = directory.listFiles(); // get the list of files from that directory

    File file;
    Scanner input;

    // process the arguments stores in args
    for (int i = 0; i < files.length; i++) 
    {
        input = new Scanner(files[i]);

        //System.out.println("\nCurrent file name: " + files[i].getName());

        // no error checking done here, add your own
        String name;
        Double score;
        while(input.hasNext())
        {
            name = "";
            while(!input.hasNextDouble())
            {
                name += input.next() + " ";
            }
            score = input.nextDouble();
            //System.out.println("Name: " + name + " Score: " + score);
            table.put(name, score);
            table1.put(name, score);
        }
    }
    System.out.println("\n");
    System.out.println(table.toString());
    System.out.println(table.size());
    //System.out.println(table1.toString());
    System.out.println(table.get("Minnesota"));
}
}

Driver Output: https://drive.google.com/file/d/0BwujWiqVRKKsNW52N1M2UllCeHc/view?usp=sharing

Example Text File:

New England 27
Indianapolis 24
Tennessee 17
Miami 7
St. Louis 17
Arizona 10
Seattle 21
New Orleans 7
NY Jets 31
Cincinnati 24
Pittsburgh 24
Oakland 21
Washington 16
Tampa Bay 10
San Diego 27
Houston 20
Jacksonville 13
Buffalo 10
Detroit 20
Chicago 16
Cleveland 20
Baltimore 3
Atlanta 21
San Francisco 19
Philadelphia 31
NY Giants 17
Minnesota 35
Dallas 17
Denver 34
Kansas City 24
Green Bay 24
Carolina 14

原文:https://stackoverflow.com/questions/38517861
更新时间:2019-09-11 07:50

最满意答案

由于您有功能的功能代码,只需将该代码包装到如下函数中:

function ConvertDate(DateInSeconds) {
    var tripbegindateseconds = DateInSeconds;
    var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
    tripbegindatefull.setUTCSeconds(tripbegindateseconds);
    var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
    var tripbeginday = tripbegindatefull.getUTCDate();
    var tripbeginyear = tripbegindatefull.getUTCFullYear();
    tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
    return tripbegindate;
}

并在这样的日期使用它:

tripBeginDate: this.ConvertDate(trip.val().begindate),
tripEndDate: this.ConvertDate(trip.val().enddate)

Since you have a function code for the functionality, just wrap that code into a function like this:

function ConvertDate(DateInSeconds) {
    var tripbegindateseconds = DateInSeconds;
    var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
    tripbegindatefull.setUTCSeconds(tripbegindateseconds);
    var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
    var tripbeginday = tripbegindatefull.getUTCDate();
    var tripbeginyear = tripbegindatefull.getUTCFullYear();
    tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
    return tripbegindate;
}

and use it on those dates like this:

tripBeginDate: this.ConvertDate(trip.val().begindate),
tripEndDate: this.ConvertDate(trip.val().enddate)

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)