-1

creating a program the a user can enter words and it pops out an acronym and that's easy but i have to use a dictionary and the keys have to make the acronym i'm given NullReferenceException don't understand why can't see a null

just using visual studio 2015 I've tried so much my minds blown can't even describe the problem all that well sorry

    private string fullSentence;
    private string[] words = new string[5];
    private Dictionary<char, string> acronymDictionary = new Dictionary<char, string>();
    public Acronym(string sentence)
    {
        fullSentence = sentence;
        string[] words = sentence.Split(' ');

    }

    public void BuildAcronym()
    {

        char[] key = new char[words.Length];
        //key = null;
        //foreach (string info in words)
        //{
            for (int i = 0; i < words.Length; i++)
            {
                key[i] = Convert.ToChar(words[i].Substring(0,1)); //this is where the problem is
            }

I expect it to run, specifically for the key chars[] to be populated by the first letter of each word in words[] so i can set key[] as the keys for the dictionary

Loocid
  • 6,112
  • 1
  • 24
  • 42
  • 1
    You're overriding your `words` member with a local variable with the same name in your constructor. `words = sentence.Split(' ');` – Loocid Mar 29 '19 at 04:07
  • Which line of code throws the exception? – mjwills Mar 29 '19 at 05:11
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mjwills Mar 29 '19 at 05:11

2 Answers2

0

words[i] can be null.

You could put a breakpoint on the line that throws and in the 'Watch' window check the value of words[i].

tymtam
  • 31,798
  • 8
  • 86
  • 126
0

please try this.

    private string fullSentence;
    private string[] words;
    private Dictionary<char, string> acronymDictionary = new Dictionary<char, string>();
    public Acronym(string sentence)
    {
        fullSentence = sentence;
        words = sentence.Split(' ');

    }

    public void BuildAcronym()
    {
        if(words != null)
        { 
        char[] key = new char[words.Length];
        //key = null;
        //foreach (string info in words)
        //{
            for (int i = 0; i < words.Length; i++)
            {
                key[i] = Convert.ToChar(words[i].Substring(0,1)); //this is where the problem is
            }
         }
     }
Hemang A
  • 1,012
  • 1
  • 5
  • 16