如果......那么...... Else Visual Basic 2012

时间:2015-06-08 20:25:42

标签: vb.net if-statement

我正在尝试在Visual Basic 2012中创建一个应用程序,我很难让它满足参数。我究竟做错了什么?每当我尝试添加Else时,它都说必须有一个If在它之前。 问题:

为大学招生办公室写一个程序。创建存储数字高中成绩点平均值和入学考试成绩的变量(例如,如果gpa> = 3.6且得分> = 60,则可以使用“和”两个不同的标准)打印消息“接受”如果学生有以下任何一项:

  • 平均成绩为3.6或以上,入学考试成绩至少为60
  • 平均成绩为3.0或以上,入学考试成绩至少为70
  • 平均成绩为2.6或以上,入学考试成绩至少为80
  • 平均成绩2.0或以上,入学考试成绩至少为90%

如果学生不符合任何资格,请打印“拒绝”。下面的图片将为您提供界面外观的参考。

    If txtGPA.Text >= 3.6 And txtAdmissionTestScore.Text >= 60 Then txtAdmissionResult.Text = "Accept"
    If txtGPA.Text >= 3.6 And txtAdmissionTestScore.Text <= 59 Then txtAdmissionResult.Text = "Reject"

    If txtGPA.Text >= 3.0 And txtAdmissionTestScore.Text >= 70 Then txtAdmissionResult.Text = "Accept"
    If txtGPA.Text >= 3.0 And txtAdmissionTestScore.Text <= 69 Then txtAdmissionResult.Text = "Reject"

    If txtGPA.Text >= 2.6 And txtAdmissionTestScore.Text >= 80 Then txtAdmissionResult.Text = "Accept"
    If txtGPA.Text >= 2.6 And txtAdmissionTestScore.Text <= 79 Then txtAdmissionResult.Text = "Reject"

    If txtGPA.Text >= 2.0 And txtAdmissionTestScore.Text >= 90 Then txtAdmissionResult.Text = "Accept"
    If txtGPA.Text >= 2.0 And txtAdmissionTestScore.Text <= 89 Then txtAdmissionResult.Text = "Reject"

    If txtGPA.Text <= 1.9 And txtAdmissionTestScore.Text <= 59 Then txtAdmissionResult.Text = "Reject"

3 个答案:

答案 0 :(得分:4)

你需要做这样的事情。注意我正在检查常见条件,然后检查子条件,子条件是接受或拒绝。因此,您只需要测试一个。

If txtGPA.Text >= 3.6 Then 
    If txtAdmissionTestScore.Text >= 60 Then 
        txtAdmissionResult.Text = "Accept"
    Else
        txtAdmissionResult.Text = "Reject"
    End If
ElseIf txtGPA.Text >= 3.0 Then   
    If txtAdmissionTestScore.Text >= 70 Then 
         txtAdmissionResult.Text = "Accept"
     Else
         txtAdmissionResult.Text = "Reject"
     Endif
ElseIf ...

End If

答案 1 :(得分:2)

这只是道格拉斯·巴宾的代码重新格式化的可读性(这显然是非常主观的!),,最后一个条件被移除,因为你不能以低于2.0的GPA录取。我还添加了支票以确保输入的GPA和测试分数分别是有效的双倍和整数:

    Dim GPA As Double
    Dim AdmissionTestScore As Integer
    If Double.TryParse(txtGPA.Text, GPA) AndAlso Integer.TryParse(txtAdmissionTestScore.Text, AdmissionTestScore) Then
        Dim shouldAccept As Boolean = _
            (GPA >= 3.6 AndAlso AdmissionTestScore >= 60) OrElse _
            (GPA >= 3.0 AndAlso AdmissionTestScore >= 70) OrElse _
            (GPA >= 2.6 AndAlso AdmissionTestScore >= 80) OrElse _
            (GPA >= 2.0 AndAlso AdmissionTestScore >= 90)
        txtAdmissionResult.Text = If(shouldAccept, "Accept", "Reject")
    Else
        MessageBox.Show("Invalid GPA and/or Admission Test Score!")
    End If

答案 2 :(得分:0)

Dim shouldAccept As Boolean = (txtGPA.Text >= 3.6 AndAlso txtAdmissionTestScore.Text >= 60) OrElse _ 
    (txtGPA.Text >= 3.0 AndAlso txtAdmissionTestScore.Text >= 70) OrElse _
    (txtGPA.Text >= 2.6 AndAlso txtAdmissionTestScore.Text >= 80) OrElse _
    (txtGPA.Text >= 2.0 AndAlso txtAdmissionTestScore.Text >= 90)

txtAdmissionResult.Text = If(shouldAccept, "Accept", "Reject")