C#Console - Console.ReadLine返回错误的输出

时间:2013-04-24 10:19:32

标签: c# .net console-application

我这里有一个C#控制台应用程序,当我允许用户输入一定数量的记录时,程序将生成一个报价编号。这是我在我的程序中实现之前测试我制定的算法。

例如,当我输入23(假设这是数据库中的当前记录计数)时,程序将输出“CQ-13-04-0023”。但我得到了“CQ-13-04-0051”的输出。我的目标是当给定报价编号中的序列号达到9999时,当数据库中的记录数达到10000及以上时,它将重置为0001。

这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        string QuoteRefNum = "";
        string seriesCount = "";
        DateTime year = DateTime.Now;
        string strYear = year.ToString("yy");
        string strMonth = year.ToString("MM");

        Console.Write("Input the number of records: ");
        int numberOfRecords = Convert.ToInt32(Console.Read());

        numberOfRecords++;

        if (numberOfRecords == 0)
        {
            seriesCount = "000" + numberOfRecords++;
        }
        else if (numberOfRecords >= 1 && numberOfRecords <= 9)
        {
            seriesCount = "000" + numberOfRecords;
        }
        else if (numberOfRecords >= 10 && numberOfRecords <= 99)
        {
            seriesCount = "00" + numberOfRecords;
        }
        else if (numberOfRecords >= 100 && numberOfRecords <= 999)
        {
            seriesCount = "0" + numberOfRecords;
        }
        else if (numberOfRecords >= 1000 && numberOfRecords <= 9999)
        {
            seriesCount = numberOfRecords.ToString();
        }
        else if (numberOfRecords >= 10000 && numberOfRecords <= 99999)
        {
            string newSetOfRecords = numberOfRecords.ToString();
            int tempNumber = 0;

            newSetOfRecords.Remove(0, 1);
            tempNumber = Convert.ToInt32(newSetOfRecords);

            if (tempNumber == 0)
            {
                seriesCount = "000" + tempNumber++;
            }
            else if (tempNumber >= 1 && tempNumber <= 9)
            {
                seriesCount = "000" + tempNumber;
            }
            else if (tempNumber >= 10 && tempNumber <= 99)
            {
                seriesCount = "00" + tempNumber;
            }
            else if (tempNumber >= 100 && tempNumber <= 999)
            {
                seriesCount = "0" + tempNumber;
            }
            else if (tempNumber >= 1000 && tempNumber <= 9999)
            {
                seriesCount = tempNumber.ToString();
            }

        }

        QuoteRefNum = "CQ" + strYear + "-" + strMonth + "-" + seriesCount;

        Console.WriteLine("The quote reference number is: " + QuoteRefNum);
    }
}

2 个答案:

答案 0 :(得分:1)

这一行是问题所在:

        int numberOfRecords = Convert.ToInt32(Console.Read());

返回ASCII值。

将其更改为:

        int numberOfRecords;
        Int32.TryParse(Console.ReadLine(), out numberOfRecords);

删除numberOfRecords++

解释发生了什么:

您获得51的原因是,当您输入23时,记录数设置为50,然后您通过{{将变量增加到51 1}}

答案 1 :(得分:1)

当您键入23时问题为Console.Read();结束输入键Read()将返回第一个输入字符2的键值。 ASCII 2的字符值为50

所以你会在numberOfRecords++之后得到51

Console.Read();更改为Console.ReadLine();并删除numberOfRecords++