私は C# を初めて使用します。成績文字 (A、B、C、D、F) を検証する TextBox に問題があります。現時点では、以下のコードは 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;
}
}