我是編程新手,我決定根據用戶輸入創建一個隨機字生成器來給自己一個挑戰。 我試圖把用戶的單詞放入數組中,然後從數組中顯示一個隨機單詞。當我運行程序時,最多可以輸入四個單詞,然後收到錯誤消息:「數組索引超出範圍。」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)]);
}
}
}
爲什麼在'while'循環的每次迭代中調整數組的大小?你可以簡單地使用'List'。 –
2014-11-24 08:09:23
我什至不知道你如何得到4個元素。這段代碼看起來會像輸入的第二個單詞一樣崩潰,因爲第一次調用Array.Resize()只是將長度設置爲1,這就是原來的樣子。 – 2014-11-24 08:20:48
@PeterDuniho看看代碼流。在第一次迭代時,他有2個'Console.Readline'(一個在while循環語句中,另一個在while循環體內)。在第二次迭代中,他再次從while循環語句中的Console.ReadLine中讀取數據,然後在while塊中嘗試分配單詞[a] = Console時崩潰。ReadLine()'(在第四次readline調用)。 – 2014-11-24 08:23:06