0
using A = System.Console;
public void point()
{
    int hour, minute;
    A.Write("Enter Time (HH:MM) = ");
    hour = A.Read();
    A.Write(":");
    minute = A.Read();
}

我希望它像

"输入时间 (HH:MM) = 12(小时输入):49(分钟输入)"

但它就像

"输入时间 (HH:MM) = 12(小时输入)
:49(分钟输入)

4

3 回答 3

3

最简单的方法(假设您正在从控制台读取,用户将输入小时然后按Enter,然后输入分钟并按Enter):

static void Main(string[] args)
        {
            int hour = 0, minute = 0;
            const int MAX_NUMBER_OF_DIGITS = 2 ;

            Console.Write("Enter Time (HH:MM) = ");
            
            // store cursor position
            int cursorLeft = Console.CursorLeft;
            int cursorTop = Console.CursorTop;
            
            // use ReadLine, else you will only get 1 character 
            // i.e. number more than 1 digits will not work
            hour = int.Parse(Console.ReadLine());

            Console.SetCursorPosition(cursorLeft + MAX_NUMBER_OF_DIGITS , cursorTop);

            Console.Write(":");

            minute = int.Parse(Console.ReadLine());

            // Nitpickers! purposefully not using String.Format, 
            // or $, since want to keep it simple!
            Console.Write("You entered: " + hour + ":" + minute);
        }

输出:

输入时间 (HH:MM) = 17:55

您进入:17:55

尽管我宁愿向您推荐更好且更不易出错的方式(用户输入 HH:MM 并按Enter一次,即输入一个字符串,包括:冒号):

static void Main(string[] args)
{
    int hour = 0, minute = 0;

    Console.Write("Enter Time in format HH:MM = ");

    string enteredNumber = Console.ReadLine();

    string[] aryNumbers = enteredNumber.Split(':');

    if (aryNumbers.Length != 2)
    {
        Console.Write("Invalid time entered!");
    }
    else
    {
        hour = int.Parse(aryNumbers[0]);
        minute = int.Parse(aryNumbers[1]);

        // Nitpickers! purposefully not using String.Format, 
        // or $, since want to keep it simple!
        Console.Write("You entered: " + hour + ":" + minute);

    }
}
于 2018-08-30T18:17:15.293 回答
1

假设 A 是控制台,您可以这样做:

    static void Main()
    {
        int hour, minute;
        char[] hourChars = new char[2];
        Console.Write("Enter Time (HH:MM) = ");
        hourChars[0] = Console.ReadKey().KeyChar;
        hourChars[1] = Console.ReadKey().KeyChar;
        var hourString = new String(hourChars);
        hour = int.Parse(hourString);
        Console.Write(":");
        minute = Console.Read();
    }
于 2018-08-30T18:04:42.040 回答
0

假设 A 是标准 c#Console那么你可以使用ReadKey而不是Read

ReadKey一次只会读取一个字符,但不会强迫您按 Enter 键,这是新行的原因。

    static void Main()
    {
        char h1, h2, m1, m2;
        Console.Write("Enter Time (HH:MM) = ");
        h1 = Console.ReadKey().KeyChar;
        h2 = Console.ReadKey().KeyChar;
        Console.Write(":");
        m1 = Console.ReadKey().KeyChar;
        m2 = Console.ReadKey().KeyChar;
    }

我将把实际值解析留作练习。

于 2018-08-30T18:04:31.613 回答