索引超出了数组错误的范围

时间:2016-04-21 01:36:58

标签: c#

public class dailyMenu          
{               

    private string day="";
    private int date = 0; 
    private static int nextDate=1;
    private string entree ="";
    private double price;
    private double calories;

    private static string [] daysOfWeek= {"Monday","Tuesday","Wednesday",
        "Thursday", "Friday", "Saturday", "Sunday"};

    private static string[] entrees = {"Beef Tenderloin Fresco", 
        "Madagascar Filet Mignon", "Filet Mignon", " Lobster Ravioli",
        "Asian Infused Braised Beef", "New Age Chicken Cordon Bleu", 
        "Short Ribs", " Beef Wellington","Fajitas", "Bacon Cheeseburger", 
        "Beef Burgandy", "Spagehetti"};

    private static double [] entreePrices= { 5.99,7.99,6.99,4.50,9.99,10.29,
        5.67,8.99, 3.99,4.78,10,79,6.98};

    private static int[] entreeMealCaloricVal= { 999,1288,770,699,450,999,1500,873, 911,
        1011, 777,500}; 

    public dailyMenu()
    {
        assignDate();
        GetDay();
        RandPopulate();
    }

    void assignDate()
    {
        date = nextDate;
        nextDate++;

        if (GetDay()== "Friday") 
        {
            nextDate += 2;
        }
    }

    void RandPopulate()
    {
        Random random = new Random();
        int randomNumber = random.Next(0,13);

        entree = entrees [randomNumber];
        price = entreePrices [randomNumber];
        calories = entreeMealCaloricVal [randomNumber];
    }
}

IDE告诉我第56,41和14行可能是问题所以我猜测它与我的随机数生成器有关。

有人可以帮我一把吗?

1 个答案:

答案 0 :(得分:2)

看起来像entreesentreeMealCaloricVal包含12个项目。这意味着它们将从0到11进行索引。

使用random.Next(0,13)将生成一个从0到12的数字。当您尝试在索引12处访问这些数组时,将抛出异常。