1

我有一个家庭作业坚持者,我需要另一双眼睛。任务是创建一个提示输入学生姓名的程序,然后遍历天数 ( String[] days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};) 数组,提示每天学习的小时数。最后,程序将显示一周学习的每日平均小时数。

我坚持使用数据输入方法:

    public void EnterHours()
    {
         // entry area header
        Console.WriteLine("Enter study hours for {0} ", name);
        for (int i = 0; i < days.Length; i++) 
        {
            Console.Write("{0}'s study hours: ", days[i]);
            string dailyHours = Console.ReadLine();
            int.TryParse(dailyHours, out hours[i]);    // problematic statement
        }
        SumHours(hours);
    }

目前,该name变量是一个已经设置好的属性;daysString[]上面的,我已经实例hours化为int[] hours;days. SumHours 是另一种方法,它接受int[] hours作为参数并遍历数组对值求和。

当我运行程序时,控制台显示

Enter study hours for John Doe

Sunday's study hours:

但无论我输入什么,我最终都会得到一个Null Reference Exception. 我还收到以下警告消息:

Warning 1   Field 'Midterm.StudentHour.hours' is never assigned to, and will always have its default value null C:\Users\Dan\Dropbox\_MATC\ITDEV115\Assignments\Midterm\StudentHour.cs  11  15  Midterm

我尝试实例化hoursasint[] hours = new int[7];但得到相同的错误,所以我怀疑这与我输出解析整数的方式有关,但我不确定除此之外应该看什么来解决问题。想法?提示?

4

4 回答 4

1

我认为这会帮助你:

        String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
        Dictionary<string, int> hours = new Dictionary<string, int>();
        for (int i = 0; i < days.Length; i++)
        {
            int dailyHours;
            Console.Write("{0}'s study hours: ", days[i]);
            while (int.TryParse(Console.ReadLine(), out dailyHours) != true)
            {
                Console.WriteLine("Wrong input,must be only numbers!!!");
                Console.Write("{0}'s study hours: ", days[i]);
            }
            //if(int.TryParse(Console.ReadLine(),out dailyHours))
            hours.Add(days[i], dailyHours);
        }

您可以使用带有这些值的枚举来代替字符串数组。

于 2013-10-06T16:40:54.313 回答
0

你的声明一定有一些错误,因为int[] hours = new int[7]不应该给你空引用异常。也可以使用返回TryParse来检查输入是否有效。以下代码适用于我:

string[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
string name = "JLe";
int[] hours = new int[7];

Console.WriteLine("Enter study hours for {0} ", name);
for (int i = 0; i < days.Length; i++) {
    Console.Write("{0}'s study hours: ", days[i]);
    string dailyHours = Console.ReadLine();

    while (!int.TryParse(dailyHours, out hours[i])) {
        Console.Write("Please try again: ");
        dailyHours = Console.ReadLine();
    }
}
SumHours(hours);
于 2013-10-06T16:25:31.590 回答
0

您的代码运行良好。这是证据。

在此处输入图像描述

于 2013-10-06T16:26:35.623 回答
0

在将值分配给它之前,您没有初始化数组“小时”。

于 2013-10-06T16:28:23.557 回答