2014-11-24 27 views
0

我是編程新手,我決定根據用戶輸入創建一個隨機字生成器來給自己一個挑戰。 我試圖把用戶的單詞放入數組中,然後從數組中顯示一個隨機單詞。當我運行程序時,最多可以輸入四個單詞,然後收到錯誤消息:「數組索引超出範圍。」C#:調整字符串數組

我可以調整數組大小的次數有限制嗎?在C#中

using System; 

namespace RandomWordGenerator 
{ 
class MainClass 
{ 
    public static void Main (string[] args) 
    { 
     Random r = new Random(); 
     string[] words = new string[1]; 
     Console.WriteLine ("Enter words for the random word generator. "); 

     int a = 0; 
     while(!(Console.ReadLine().Equals("END"))){ 
      words[a] = Console.ReadLine(); 
      a++; 
      Array.Resize(ref words, a); 
     } 

     Console.WriteLine(); 
     Console.WriteLine (words[r.Next (a)]); 
    } 
} 
} 
+2

爲什麼在'while'循環的每次迭代中調整數組的大小?你可以簡單地使用'List '。 – 2014-11-24 08:09:23

+0

我什至不知道你如何得到4個元素。這段代碼看起來會像輸入的第二個單詞一樣崩潰,因爲第一次調用Array.Resize()只是將長度設置爲1,這就是原來的樣子。 – 2014-11-24 08:20:48

+0

@PeterDuniho看看代碼流。在第一次迭代時,他有2個'Console.Readline'(一個在while循環語句中,另一個在while循環體內)。在第二次迭代中,他再次從while循環語句中的Console.ReadLine中讀取數據,然後在while塊中嘗試分配單詞[a] = Console時崩潰。ReadLine()'(在第四次readline調用)。 – 2014-11-24 08:23:06

回答

3

數組是不變,這是說他們不能創建它們後更改。

你想要的是一個List<string>,可以隨意調整大小。

class MainClass 
{ 
    public static void Main (string[] args) 
    { 
     Random r = new Random(); 
     List<string> words = new List<string>(); 
     Console.WriteLine ("Enter words for the random word generator. "); 

     int a = 0; 
     while(!(Console.ReadLine().Equals("END"))){ 
      words.Add(Console.ReadLine()); 
     } 

     Console.WriteLine(); 
     Console.WriteLine (words[r.Next(words.Count)]); 
    } 
} 

Array.Resize實際上沒有命名的非常好,因爲它的東西比實際調整大小不同。從MSDN文檔:

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.

List<>類是專爲動態調整大小的收集,並在許多情況下是不是原始陣列更好的選擇。

+0

隨意?你沒有控制。 (除非最初以大小構建) – 2014-11-24 08:11:45

+1

'Array.Resize'每次分配一個新數組並將其分配給'words'。他沒有調整當前數組的大小。 – 2014-11-24 08:11:54

+1

數組長度是不可變的。但是數組本身並不是不可變的。這是一個重要的區別,值得正確表達。 – 2014-11-24 08:16:33

1

你看到一個IndexOutOfRangeException的原因是因爲你想用一個索引來訪問數組的當前範圍之外:您正在試圖訪問words[a]

int a = 0; 
while(!(Console.ReadLine().Equals("END"))) 
{ 
    words[a] = Console.ReadLine(); 
    a++; 
    Array.Resize(ref words, a); 
} 

一次迭代後其中a = 1,但數組索引爲零基於,因此您試圖訪問words[1]其中數組只有一個元素位於words[0]索引,因爲您分配了一個新陣列Array.Resize,傳遞a (1)作爲它的大小。這就是你看到這個例外的原因。

您的解決方案存在一個問題,正如@rossipedia所述。只需使用List<T>即可。

+1

感謝您的迴應!我的程序現在可用。 – Frederick 2014-11-24 08:57:46

0

有關使用List的建議都是很好的,有效的,但直接回答您的具體問題如下 -

Array.Resize(ref words, a); 

應改爲 -

Array.Resize(ref words, a + 1); 

原因 - 你開始a=0; ,設置words[0]爲讀取值,設置爲a=1,然後要求運行時調整您的數組的大小從1到1 ..其餘部分如下所示。

+0

哦,我明白了。這也適用。謝謝。 – Frederick 2014-11-24 08:56:58