我是C#的新手,我遇到了TextBox验证成绩字母(A,B,C,D,F)的问题。现在,下面的代码将执行if语句而不是else语句,因为如果我输入一个与其条件完全匹配的成绩字母,即使在单击“确定”按钮后设置了较低的套接字,然后是上部套接字。当我输入正确的成绩字母时,它应该跳过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;
}
}
答案 0 :(得分:4)
您可以使用包含有效成绩字母的列表,而不是使用许多条件(这使得它更难以阅读):
string gradeLetter = "A";
List<string> gradeLetters = new List<string> { "A", "B", "C", "D", "F" };
if (!gradeLetters.Contains(gradeLetter))
{
// invalid grade letter
}
else
{
// carry on
}
您的代码:
if (!string.IsNullOrWhiteSpace(gradeLetter.Text) || gradeLetter.Text != "A" || gradeLetter.Text != "B" || gradeLetter.Text != "C" || gradeLetter.Text != "D" || gradeLetter.Text != "F")
永远都是真的。假设等级为B.它将对gradeLetter.Text != "A"
进行检查,短路,并且为真,因为“B”!=“A”。
答案 1 :(得分:2)
当前if语句的问题是有效输入仍然会变为无效。如果输入是“B”,它将看到它不是“A”(在你的if语句中),这意味着整个标准都是真的。
将您的if语句更改为:
if (string.IsNullOrWhiteSpace(gradeLetter.Text) || !(gradeLetter.Text == "A" || gradeLetter.Text == "B" || gradeLetter.Text == "C" || gradeLetter.Text == "D" || gradeLetter.Text == "F"))
基本上问“你的输入是空的还是输入不是A,B,C,D或F?
答案 2 :(得分:2)
您也可以使用词典方法:
gradeLetter.Text = gradeLetter.Text.ToUpper();
IDictionary<string, double> grades = new Dictionary<string, double>
{
{"A", 4.0},
{"B", 3.0},
{"C", 2.0},
{"D", 1.0},
{"F", 0.0}
};
if (!grades.ContainsKey(gradeLetter.Text)){
MessageBox.Show("Invalid grade letter or has an empty textbox!", "Caution!", MessageBoxButton.OK);
}
else{
gradeW = grades[gradeLetter.Text];
// other stuff
}