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(分钟输入(
最简单的方法(假设您正在从控制台读取,并且用户将输入小时然后按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);
}
}
假设 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();
}
假设 A 是标准的 c#Console
那么您可以使用ReadKey
而不是Read
ReadKey
一次只会读取一个字符,但它不会强迫您按回车键,这是新行的原因。
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;
}
我将实际值解析作为练习。