C#为循环中的每个数字添加计数器

时间:2015-09-24 16:35:38

标签: c# counter

我正在编写一个程序,该程序将用户数据值1-10并存储到数组中。我试图弄清楚如何添加一个计数器,这个计数器允许我输出每个数字的输入次数以及输入的无效数字的数量。

    class Program
{
    static void Main(string[] args)
    {
        int[] data = GetData();
    }

    private static int[] GetData()
    {
        int[] dataArray = new int[100];
        int n = 0;
        int intValue = 0;

        while (true)
        {
            Console.WriteLine("Enter a number 0-10 (Q to end)");
            string lineValue = Console.ReadLine();

            if (lineValue.ToLower().Trim().Equals("q"))
            {
                break;
            }

            if (!int.TryParse(lineValue, out intValue))
            {
                Console.WriteLine("INVALID DATA - Try again.");
                continue;
            }

            if (intValue < 0 || intValue > 10)
            {
                Console.WriteLine("NUMERIC DATA OUT OF RANGE - Try again.");
                continue;
            }

            dataArray[++n] = intValue;
            dataArray[0] = n;
        }
        return dataArray;
    }
}

4 个答案:

答案 0 :(得分:2)

您可以在while条件之前为无效数字设置计数器。

int invalidNumbersCounter = 0;

然后,每次输入无效时,您都可以递增此计数器:

if (!int.TryParse(lineValue, out intValue))
{
    Console.WriteLine("INVALID DATA - Try again.");
    invalidNumbersCounter++;  
    continue;
}

关于你的另一个问题,每个数字多少次,你可以使用普通的LINQ来做这个伎俩。

static void Main(string[] args)
{
    int[] data = GetData();

    var statistics = data.GroupBy(x=>x)
                         .Select(gr => new 
                         { 
                             Number = gr.key, 
                             Times = gr.Count() 
                         });

    foreach(var statistic in statistics)
    {
        Console.WriteLine(String.Format("The number {0} found {1} times in you array", statistic.Number, statistic.Times));
    }
}

上述查询的结果将是一系列具有两个属性的匿名类型的对象,即该数字在数组中的数量和数量。

更新

为了避免计算用户未输入的值,并且本质上是数组的初始值,我们可以在创建数组时将数组的值初始化为-1,如下所示:

int[] dataArray = Enumerable.Repeat(-1, 100).ToArray();

然后我们必须将linq查询更新为以下内容:

 var statistics = data.Skip(1)
                      .Where(number => number!=-1)
                      .GroupBy(x=>x)
                      .Select(gr => new 
                      { 
                          Number = gr.key, 
                          Times = gr.Count() 
                      });

答案 1 :(得分:1)

您已经有一个计数器(n)的示例,您可以将其用作记录无效输入数量的示例。只需在if块中增加它:

if (intValue < 0 || intValue > 10)
        {
            Console.WriteLine("NUMERIC DATA OUT OF RANGE - Try again.");
            myInvalidCounter ++;
            continue;
        }

要计算输入的每个数字 - 您可以分析dataArray中存储的数据。

编辑:我刚刚注意到你有两个无效数据的例子 - 糟糕的原始数据和超出范围的数据 - 你需要设置适当的计数器 - 可能是一个或共享一个等等。

答案 2 :(得分:1)

你可以这样做:

public class Program
{
    public static void Main(string[] args)
    {
        // note updated to use a list rather than array (just preference)
        List<int> data = GetData();         
    }

    private static List<int> GetData()
    {
        List<int> list = new List<int>();
        int intValue = 0;
        int invalidAttempts = 0; // added to keep track of invalid values

        while (true)
        {
            Console.WriteLine("Enter a number 0-10 (Q to end)");
            string lineValue = Console.ReadLine();

            if (lineValue.ToLower().Trim().Equals("q"))
            {
                break;
            }

            if (!int.TryParse(lineValue, out intValue))
            {
                Console.WriteLine("INVALID DATA - Try again.");
                invalidAttempts++;
                continue;
            }

            if (intValue < 0 || intValue > 10)
            {
                Console.WriteLine("NUMERIC DATA OUT OF RANGE - Try again.");
                invalidAttempts++;
                continue;
            }

            list.Add(intValue);
        }

        Console.WriteLine("Invalid attempts {0}", invalidAttempts);

        // this is using linq to group by the individual numbers (keys),
        // then creates an anon object for each key value and the number of times it occurs.
        // Create new anon object numbersAndCounts
        var numbersAndCounts = list
            // groups by the individual numbers in the list
            .GroupBy(gb => gb)
            // selects into a new anon object consisting of a "Number" and "Count" property
            .Select(s => new {
                Number = s.Key,
                Count = s.Count()
            });

        foreach (var item in numbersAndCounts)
        {
            Console.WriteLine("{0} occurred {1} times", item.Number, item.Count);
        }

        return list;
    }
}

请注意我使用的是list而不是array,我觉得它们更容易使用。

工作演示:

https://dotnetfiddle.net/KFz1UY

  

是否可以按数字顺序输出?现在它只显示先输入的数字。例如1,7,7,4将是1:1 7:2 4:1,我怎么能改变这个去1:1 4:1 7:2?

当然有可能!见下文(和更新的原始演示)

我刚改变了:

    var numbersAndCounts = list
        .GroupBy(gb => gb)
        .Select(s => new {
            Number = s.Key,
            Count = s.Count()
        });

为:

    var numbersAndCounts = list
        .GroupBy(gb => gb)
        .Select(s => new {
            Number = s.Key,
            Count = s.Count()
        })
        .OrderBy(ob => ob.Number);

答案 3 :(得分:-2)

C#为房地产经纪人创建一个应用程序,其中包括他们库存中拥有的所有房屋。库存清单应包括房屋地址,颜色,销售价格和房间数量。启动控制台应用程序后,显示所有可用清单。 在控制台应用程序中包括以下内容: 类 采集 循环 评论