C#帮助。面向对象+数组索引

时间:2018-02-06 14:07:43

标签: c# arrays object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MonthlySales
{
    class Program
{
    static void Main(string[] args)
    {
        int num;
        double[] sales = {0};
        Inputs(out num, sales);
        CLASS obj = new CLASS();
        obj.setNumMonths(num);
        obj.setSales(sales);
        obj.Process();
        Outputs(obj);
        Console.Read();

    }

    public static void Inputs(out int a, params double[] b)
    {
        Console.Write("Enter number of sales: ");
        a = Convert.ToInt32(Console.ReadLine());

        for (int i = 0; i < a; i++)
        {
            Console.Write("Please enter sale #{0}: ", i + 1);
            b[i] = Convert.ToDouble(Console.ReadLine());
        }
    }

    public static void Outputs(CLASS obj)
    {
        for (int i = 0; i < obj.getNumMonths(); i++)
        {
            Console.WriteLine("Sale # {0} was {1:C2} and contributed {2:P2}", i + 1, obj.getSales()[i], obj.prop_Contrib);
        }
        Console.WriteLine("Total sum of sales is {0:C2}", obj.prop_Total);
    }

}

}

CLASS.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MonthlySales
{
class CLASS
{
    int numMonths, i;
    double[] sales;
    double total, contrib;

    public CLASS() { } // def constructor

    public CLASS(int a, double[] b) //constructor
    {
        numMonths = a;
        sales = new double[numMonths];
        sales = b;
    }

    public void setNumMonths(int a) //setter
    {
        numMonths = a;
    }

    public void setSales(double[] a) //setter
    {
        sales = a;
    }

    public int getNumMonths() //getter
    {
        return numMonths;
    }

    public double[] getSales() //getter
    {
        return sales;
    }

    public double prop_Total //property
    {
        get { return total; }
    }

    public double prop_Contrib //property
    {
        get { return contrib; }
    }

    public void Process()
    {
        total = 0;
        for(i=0; i < numMonths; i++)
        {
            total = total + sales[i];
        }
        contrib = sales[i] / total;

    }
}

}

当程序询问用户的输入时,它运行良好。但是当显示输出时,控制台会自动关闭。它在Inputs(out num, sales);b[i] = Convert.ToDouble(Console.ReadLine());(位于主程序中)中引发错误。它说

  

System.IndexOutOfRangeException:'索引超出了数组的范围。'

任何见解都会有所帮助。非常感谢。

0 个答案:

没有答案