2015-01-31 322 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

相關問題