当它应该只运行一次时,方法运行两次

时间:2017-01-31 23:15:43

标签: c#

class Myclass
{
    public string Driver1()
    {
        string a = "";

        Console.Write("Please enter drivers name: ");
        a = Console.ReadLine();

        return a;
    }  
    public int numberOfTrips()
    {
        int a = 0;
        {
            Console.Write("Enter the number of trips: ");
            a = Convert.ToInt32(Console.ReadLine());
        }
        return a;
    }   
    public List<float> Payments()
    {
        List<float> a = new List<float>();
        float input;

        for (int i = 0; i<numberOfTrips(); i++)
        {
            Console.Write("Enter payment {0}: ", (1 + i));
            input = float.Parse(Console.ReadLine());
            Console.WriteLine("Payment added");
            a.Add(input);
        }

        return a;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Myclass a = new Myclass();

        string name = a.Driver1();
        int trip = a.numberOfTrips();
        float total = a.Payments().Sum();

        Console.WriteLine("\nDriver: {0}\n" + "Number of trips: {1}\n" + "Total payment: {2}\n", name, trip, total);
    }
}

我遇到的问题是“public int numberOfTrips()”方法在到达包含for循环的方法之前运行了两次。我认为这与我在for循环中使用它的事实有关,以指定循环何时应该停止。我猜我做错了所以我怎么纠正这个?我需要用户能够设置要求付款的次数。

感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

您可以尝试在MyClass中创建实例变量或静态变量,而不是在Main()和Payments()中调用numberOfTrips()。然后,您可以在计算完所有付款后从该变量中获取行程数。

答案 1 :(得分:0)

这是正确的。第一次运行是在Main中设置&#39;旅行&#39;变量。它第二次运行在Payments中,在for循环声明中。

答案 2 :(得分:0)

只需将numberOfTrips中的数字作为参数传递给Payments

public List<float> Payments(int tripCount)
{
    List<float> a = new List<float>();
    float input;

    for (int i = 0; i < tripCount; i++)
    {
        Console.Write("Enter payment {0}: ", (1 + i));
        input = float.Parse(Console.ReadLine());
        Console.WriteLine("Payment added");
        a.Add(input);
    }

    return a;
}

Main方法中:

Myclass a = new Myclass();

string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments(trip).Sum();