【发布时间】:2023-04-10 13:18:01
【问题描述】:
我正在尝试创建一个小型 powershell 程序,它会询问您一个随机单词,您必须翻译它。我正在使用两个数组的索引来确定答案是否正确。
每当用户输入正确或错误的答案时,文本框都应该增加它的值,以显示到目前为止用户有多少正确和错误。到目前为止,该程序可以正常工作,但计数器却没有。此时计数器只增加到 1 并且不会超过 1。我错过了什么吗?
我认为问题可能是 PowerShell 总是调用来自外部 countercorrect 和 counterwrong 的值,即 0 但我如何解决它只调用递增的值?
$QuestionArray = New-Object System.Collections.ArrayList
$AnswerArray = New-Object System.Collections.ArrayList
$countercorrect = 0
$counterwrong = 0
#word array
$QuestionArray.Add("word1")
$QuestionArray.Add("word2")
$QuestionArray.Add("word3")
#solution array
$AnswerArray.Add("answer1")
$AnswerArray.Add("answer2")
$AnswerArray.Add("answer3")
#Function to display a new word
function Question {
$global:RandomQuestion = $QuestionArray | Get-Random
$SearchedTextbox.Text = $global:RandomQuestion
}
$InputTextbox.Add_KeyDown({
if ($_.KeyCode -eq "Enter") {
#Get User Guess
$Answer = $InputTextbox.Text
#Get Solution array Index
$IndexPositionQuestion = [array]::indexof($QuestionArray, $global:RandomQuestion)
#Get User answer array Index
$IndexPositionAnswer = [array]::indexof($AnswerArray, $Answer)
#Check if both indexes match
If($IndexPositionAnswer -eq $IndexPositionQuestion){
#this fails / doesn't go above 1
$RightTextBox.Text = countercorrect++
Question
}else{
#this fails / doesn't go above 1
$WrongtTextBox.Text = counterwrong++
Question
}
}
})
我尝试使用单独的函数来增加它的值,但即使这样也只增加到 1。
【问题讨论】:
-
代码缺少一些变量标识符:
$RightTextBox.Text = countercorrect++。这些只是复制粘贴编辑错误吗? -
$countercorrect++->$script:countercorrect++,$counterwrong++->$script:counterwrong++。增加/减少计数器时,您处于函数的范围内(未经测试,但我非常有信心)。是的,正如@vonPryz 提到的,你错过了几个$标志。 -
谢谢!是的,我的错,他们确实是复制粘贴错误。 @sodawillow 非常感谢我之前尝试使用 $script:countercorrect++ 的解决方案,但只是在另一个函数内部,它只是出于某种原因删除了整个值。但是在函数之外使用它就像一个魅力!
标签: powershell counter