我是 C# 新手,我在使用 TextBox 验证等级字母(A、B、C、D、F)时遇到问题。现在,如果我输入一个完全符合其条件的等级字母,下面的代码将执行 if 语句而不是 else 语句,即使在单击 OK 按钮后小写然后大写也是如此。当我输入正确的等级字母时,它应该跳过 if 并继续执行 else 语句,但是我没有看到有什么问题。
private void Button_Click(object sender, RoutedEventArgs e)
{
//automatically convert gradeLetter inputs to uppercase
gradeLetter.Text = gradeLetter.Text.ToUpper();
//check if gradeLetter entered is valid
if (!string.IsNullOrWhiteSpace(gradeLetter.Text) || gradeLetter.Text != "A" || gradeLetter.Text != "B" || gradeLetter.Text != "C" || gradeLetter.Text != "D" || gradeLetter.Text != "F")
{
MessageBox.Show("Invalid grade letter or has an empty textbox!", "Caution!", MessageBoxButton.OK);
}
else
{
// switch statement to determine which 'gradeLetter' is being used
// and assign numerical numbers to 'gpa' to then be calculated.
switch (gradeLetter.Text)
{
case "A": gradeW = 4.0;
break;
case "B": gradeW = 3.0;
break;
case "C": gradeW = 2.0;
break;
case "D": gradeW = 1.0;
break;
case "F": gradeW = 0.0;
break;
default: // do nothing
break;
}
double result = (GPA += gradeW); //add to the gpa
gCounter++; // increment the gpa entered
result /= gCounter; // divide by the number of gpa entered
result = Math.Round(result, 2, MidpointRounding.AwayFromZero); //round the result to two decimal places
gpa.Text = result.ToString(); //convert result from int to string and display in 'gpa' TextBlock
//append the input grade letters to 'gradeEntered' TextBlock
gradeEntered.Text += gradeLetter.Text + System.Environment.NewLine;
}
}