2015-01-31 323 views
-1

这是我的代码。我知道这个错误很常见,但我仍然无法弄清楚为什么会出现这个错误。我试图从乐器阵列中的单词中删除元音。我做了一个If语句来确保错误不是由Instrument [a]为空造成的。错误:“未将对象引用设置为对象的实例”

 string[] Instruments = new String[7]; 
     Instruments[0] = "hej"; 
     Instruments[1] = "cello"; 
     Instruments[2] = "guitar"; 
     Instruments[3] = "violin"; 
     Instruments[4] = "double bass"; 
     Instruments[5] = "drums"; 

     string[] Vowels = new String[9]; 
     Vowels[0] = "e"; 
     Vowels[1] = "y"; 
     Vowels[2] = "u"; 
     Vowels[3] = "i"; 
     Vowels[4] = "o"; 
     Vowels[5] = "å"; 
     Vowels[6] = "a"; 
     Vowels[7] = "æ"; 
     Vowels[8] = "ø"; 

     string message = "start: "; 

     for (int a = 0; a < Instruments.Length; a++) 
     { 

      string InstrumentCurrent = Instruments[a]; 
      Console.WriteLine(Instruments[a]); 
       for (int i = 0; i < Vowels.Length; i++) 
       { 
        if (InstrumentCurrent != null); 
        { 
        //InstrurmentCurrent = InstrumentCurrent += ""; (If I uncomment this, the code works fine) 
        InstrumentCurrent = InstrumentCurrent.Replace(Vowels[i], ""); 
        } 

       } 
       message += InstrumentCurrent; 
       message += ", "; 

     } 

     MessageBox.Show(message); 
+0

异常消息应该告诉你确切的行号。 – 2015-01-31 22:31:11

+0

@MAV我认为这可能是因为该名称可能不包含如此产生的元音,但它实际上是语法(请参阅下面的答案)。 – zaitsman 2015-01-31 22:32:10

+0

您为'Instruments'变量创建了7个字符串的数组,但只初始化了6个字符串... – 2015-01-31 22:32:57

回答

1

你的问题是非常非常有趣的 - 看看这个行:

if (InstrumentCurrent != null); 

删除在最后的分号,然后再试一次。

+0

它工作!谢谢。但是如果我删除整个if语句,我仍然会得到对我来说没有意义的错误。 – 2015-01-31 22:37:20

+0

那就是@JeffMercado的注释 - 你的数组大小为7,但你只能初始化6个成员。所以要么增加一个乐器,要么改变'string [] Instruments = new String [6];' – zaitsman 2015-01-31 22:38:43

相关问题