所以我试图在vb.net中使用三元运算符来运行一个石头剪刀游戏,但无论我如何设置它,我得到错误的结果(继续输出相同的结果,无论如何实际结果应该是IE,R vs P =输,R vs S =输,R vs R输=
我最初尝试使用结果/绘制bool作为占位符,在结尾显示结果,并在紧跟在IIF之后的ifs中添加了一个退出开关但仍然会导致循环不更改结果。
Public Class Form1
Const ROCK As Integer = 1
Const PAPER As Integer = 2
Const SCISSORS As Integer = 3
Dim computerThrow As Integer
Dim comThrow As String = "Rock"
Dim wins As Integer
Dim losses As Integer
Dim draws As Integer
Dim outcome As Boolean = True
Dim draw As Boolean = True
'Spent two days debugging, kept getting more broken. hmm
Private Sub btnThrow_Click(sender As Object, e As EventArgs) Handles btnThrow.Click
'Generate computer throw
Randomize()
computerThrow = Int(3 * Rnd() + 1)
'Select case block
Select Case computerThrow
Case ROCK
comThrow = "rock"
IIf(Me.radRock.Checked = True, draw = True, 1 = 1) 'Ternarys to decide outcome/draw
If draw = True Then 'If to decide whether to exit or not
Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
draws = draws + 1
End If
IIf(Me.radPaper.Checked = True, outcome = True, 1 = 1)
If outcome = True Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
wins = wins + 1
End If
IIf(Me.radScissors.Checked = True, outcome = False, 1 = 1)
If outcome = False And draw = False Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
losses = losses + 1
End If
Case PAPER
comThrow = "paper"
IIf(Me.radRock.Checked = True, outcome = False, 1 = 1)
If outcome = False And draw = False Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
losses = losses + 1
End If
IIf(Me.radPaper.Checked = True, draw = True, 1 = 1)
If draw = True Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
draws = draws + 1
End If
IIf(Me.radScissors.Checked = True, outcome = True, 1 = 1)
If outcome = True Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
wins = wins + 1
End If
Case SCISSORS
comThrow = "scissors"
IIf(Me.radRock.Checked = True, outcome = True, 1 = 1)
If outcome = True Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", you win!"
wins = wins + 1
End If
IIf(Me.radPaper.Checked = True, outcome = False, 1 = 1)
If outcome = False And draw = False Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", you lose!"
losses = losses + 1
End If
IIf(Me.radScissors.Checked = True, draw = True, 1 = 1)
If draw = True Then
Me.lblWinner.Text = "Computer throws " + comThrow + ", it's a draw!"
draws = draws + 1
End If
End Select
Me.lblResults.Text = "wins: " + wins.ToString() + " Lose: " + losses.ToString() + " draws: " + draws.ToString()
End Sub
End Class
答案 0 :(得分:5)
IIF不是VB.NET中的三元运算符。 IIF is a function评估真实部分和虚假部分。这意味着,无论选中复选框的状态如何,都会始终执行IIF函数的真实部分,因此您始终将变量赋值为true或false。
相反,VB.NET中的conditional ternary operator是 If(表达式,true部分,false部分),它使用shortcircuit evaluation来选择表达式值。 因此,您应该以这种方式重写代码
draw = If(Me.radRock.Checked, True, False)
If draw Then
....
但此时你可以简单地写一下
draw = Me.radRock.Checked
If draw Then
....
或
outcome = Not Me.radRock.Checked
....