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
最满意答案
由于您有功能的功能代码,只需将该代码包装到如下函数中:
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)
相关问答
更多-
您可以使用字典将年份和月份保存为键,将列表中的相对天数保存为值,然后您可以对按年份和月份分类的项目执行任何操作。 >>> dates = [['2014', '11', '14'], ['2014', '10', '13'], ['2014', '10', '01'], ['2014', '12', '01'], ['2013', '12', '01'], ['2013', '12', '09'], ['2013', '10', '01'], ['2013', '10', '05'], ['2013', ' ...
-
假设y, m, d都是int ,怎么样? CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME) 请参阅SQL Server 2012及其以上的其他答案 Assuming y, m, d are all int, how about: CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varch ...
-
实际上你可以使用你在问题中所说的new Date.getMonth()来使它工作。 请参阅以下代码: import DS from 'ember-data'; import Ember from 'ember'; export default DS.Model.extend({ createdAt: DS.attr('string', { defaultValue() { return new Date(); } }), cre ...
-
由于您有功能的功能代码,只需将该代码包装到如下函数中: 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(tripbeg ...
-
如果 monthStr = months[month-1] 有索引错误,这意味着month小于1或大于12.您可以在此行之前检查它是否在正确的范围内。 几点说明 eval是危险的,在这种情况下不需要。 您可以使用split , map和int来提取整数。 如果您想自己编写日期,可以使用%02d format显示日期 strftime和strptime正是你想要的。 它们将字符串解析为日期时间并以任何给定格式显示datetime时间。 日历已经有month_name 。 该列表有13个元素,第一个 ...
-
Parse Date,Month,and Year from Javascript“Date”form(Parse Date, Month, and Year from Javascript “Date” form)[2023-11-11]
你最好的选择,如果你接受输入并将其转换为日期 ,按部分或作为Date对象分割,就是通过传入输入值来构造一个新的Date对象: var input = document.getElementById( 'id' ).value; var d = new Date( input ); if ( !!d.valueOf() ) { // Valid date year = d.getFullYear(); month = d.getMonth(); day = d.getDate(); ... -
如何从年,月,星期和星期几获取日期?(How to get a date from year, month, week of month and Day of week ? C#)[2022-06-03]
今年的总统日是2月15日,所以这是正确的。 我有劳动节这样工作:第一部分我不得不假设你想将微软的DateTime(星期日= 0)翻译成你的星期日= 1枚举。 public static DayOfWeek GetOneBasedDayOfWeek(DateTime date) // date = 9/1/2016 12:00:00 AM { // returns Thursday return (DayOfWeek)((int)date.DayOfWeek + ... -
您错误地使用了Date#getYear : 返回一个值,该值是从包含或以此Date对象表示的时刻开始的年份减去1900的结果,如本地时区中所解释的那样。 getYear()的偏移量为1900,使用LocalDate.of(year, month, day)时必须添加。 这就是为什么你计算的瞬发的年份是115。 Instant instant = time.atDate(LocalDate.of(date.getYear() + 1900, date.getMonth(), date.getDa ...
-
您应该使用DateTimeClass的createFromFormat format('d'); // 09 echo "Month : ".$date->format('m'); //03 echo "Year : ".$date->format('Y'); ...
-
没有没有jQuery方法,但你可以使用纯JS。 var date = new Date(2015, 9, 28); 注意:对于此特定示例,月份从0开始,因此上例中的9表示10月。 在这里阅读更多相关信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date No there isn't a jQuery method for this but you can do it with pure ...