-
October 10th, 2008, 12:05 AM
#1
error: "Null reference" when I make dictionary with HashTable in C#
I try to use C# to illustrate HashTable algorithm. I decide to make a small dictionary in ConsoleApplication(VS2008).
But my problem is: error "Null reference" in "if(hashtable[i]!=null) " when I build program.
I just beginner in C#, please show me the reason for that.Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//#define TRUE 1
//#define FALSE 0
//#define M 26
namespace ConsoleApplicationForDict
{
class Node
{
public string word;
public string mean;
public Node next;
public Node()
{
next = null;
}
//make a new node
public Node GetNode(String word, String mean)
{
Node p;
p = new Node();
p.word = string.Copy(word);
p.mean = string.Copy(mean);
return p;
}
//HashFunction
public int HF(string word)
{
char []firstchar = word.ToUpper().ToCharArray(0,1);
int value = firstchar[0];
return ((value - 65) % 26);
}
}
class LinkList: Node
{
public Node[] hashtable = new Node[26];
public LinkList() { }
public void InsertNode(Node p)
{
int i = HF(p.word);
p.next = hashtable[i];
hashtable[i] = p;
}
//print list
public void PrintList(Node list)
{
Node temp = list;
while (temp != null)
{
Console.WriteLine("word:{0}", temp.word);
Console.WriteLine("mean:{0}", temp.mean);
temp = temp.next;
}
}
}
class Dictionary: LinkList
{
public Node[] hashtable;
public Dictionary() {/* Node[] hashtable = new Node(26);*/ }
public void MakeDictionary()
{
string word, mean;
Console.WriteLine("Nhap word:");
word = Console.ReadLine();
Console.WriteLine("Nhap mean:");
mean = Console.ReadLine();
//Node p = new Node();
LinkList linklist = new LinkList();
Node p = linklist.GetNode(word, mean);
linklist.InsertNode(p);
}
public void DisplayDictionary()
{
for (int i = 0; i < 26; i++)
if(hashtable[i]!=null)
PrintList(hashtable[i]);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary dict = new Dictionary();
dict.MakeDictionary();
dict.DisplayDictionary();
}
}
}
-
October 10th, 2008, 04:10 AM
#2
Re: error: "Null reference" when I make dictionary with HashTable in C#
in the Dictionary class, you did not initialize hashtable. (use new operator)
-
October 10th, 2008, 08:52 AM
#3
Re: error: "Null reference" when I make dictionary with HashTable in C#
thank you, I have solved my problems
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|