星期一的用户输入日期应以“ 1”返回,而整数输入的“ 1”则应以“ Monday”返回。现在,零代表星期一。我的理解是,我需要向其添加1,因此需要如下所示的+1,但这只会使事情更加复杂。 任何输入表示赞赏。
string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
public Form1()
{
InitializeComponent();
}
private void BtnGetNum_Click(object sender, EventArgs e)
{
string dayName = (txtDayName.Text);
int dayIndex, dayNumber;
dayIndex = Array.IndexOf(days, dayName);
lblNumOut.Text = dayIndex.ToString();
}
private void BtnGetDay_Click(object sender, EventArgs e)
{
int dayNumber;
if (int.TryParse(txtDayNum.Text, out dayNumber) == false || dayNumber < 1 || dayNumber > 7)
{
MessageBox.Show("Must be a valid number from 1 to 7.");
}
lblNameOut.Text = (days[dayNumber + 1]);
}
答案 0 :(得分:0)
应该是这样的:
private void BtnGetNum_Click(object sender, EventArgs e)
{
string dayName = txtDayName.Text;
int dayIndex;
//To find the index of the day ignoring the case, so the input can be monday, Monday, mOnDaY...etc.
dayIndex = Array.FindIndex(days, a => a.Equals(dayName, StringComparison.CurrentCultureIgnoreCase));
//Check if the input is a valid day name:
if(dayIndex == -1)
{
MessageBox.Show("Enter correct day name.");
return;
}
lblNumOut.Text = (dayIndex + 1).ToString();
}
private void BtnGetDay_Click(object sender, EventArgs e)
{
int dayNumber;
if (!int.TryParse(txtDayNum.Text, out dayNumber) || dayNumber < 1 || dayNumber > 7)
{
MessageBox.Show("Must be a valid number from 1 to 7.");
return;
}
//0-based index. When the input say = 3, that means the value position in the array is 3 - 1 = 2.
lblNameOut.Text = days[dayNumber - 1];
}
祝你好运