我有一个子试图在数据库中获取随机食物,得到这些食物的卡路里总和,并检查它们是否不会超过所需的卡路里。
子工作的大部分时间,但有时会出现此错误。 这是我的代码。它有点长。
Private Sub lunchgenerate()
Dim grams As Integer = DSgrams.Tables("grams").Rows(0).Item("grams")
Dim grams1 As Integer = DSricegrams.Tables("ricegrams").Rows(0).Item("grams")
Dim grams2 As Integer = DSgrams2.Tables("grams").Rows(0).Item("grams")
Dim calorieval As Decimal = foodcalories * grams
Dim calorieval1 As Decimal = ricecalories * grams1
Dim calorieval2 As Decimal = foodcalories2 * grams2
Dim carbval As Decimal = foodcarb * grams
Dim carbval1 As Decimal = ricecarb * grams1
Dim carbval2 As Decimal = foodcarb2 * grams2
Dim proteinval As Decimal = foodprotein * grams
Dim proteinval1 As Decimal = riceprotein * grams1
Dim proteinval2 As Decimal = foodprotein2 * grams
Dim fatval As Decimal = foodfat * grams
Dim fatval1 As Decimal = ricefat * grams1
Dim fatval2 As Decimal = foodfat2 * grams
Dim caloriepercent As Decimal = usercalories * 0.5
Dim mincalories As Decimal = caloriepercent - 300
Dim proteinpercernt As Decimal = userprotein * 0.5
Dim minprotein As Decimal = proteinpercernt - 20
Dim counter As Integer = 0
Dim counter1 As Integer = 0
Dim foodcalorietotal As Decimal = calorieval + calorieval1 + calorieval2
Dim foodproteintotal As Decimal = proteinval + proteinval1 + proteinval2
Dim carbtotal As Decimal = carbval + carbval1 + carbval2
Dim foodfattotal As Decimal = fatval + fatval1 + fatval2
If foodcalorietotal < mincalories Or foodcalorietotal > caloriepercent Then
counter = 0
Else
counter = 1
End If
If foodproteintotal < minprotein Or foodproteintotal > proteinpercernt Then
counter1 = 0
Else
counter1 = 1
End If
If counter = 1 And counter1 = 1 Then
'output to the form
Else
**lunchgenerate()**
End If
End If
End Sub
我认为错误是再次调用lunchgenerate()sub时的错误。
但就像我说的那样,大部分时间都有效,但有时会冻结,然后会出现此错误,然后突出显示我的代码的第一行
Dim DAlunchcategory As New SqlDataAdapter(lunchquery, CN)
Dim DSlunchcategory As New DataSet
DAlunchcategory.Fill(DSlunchcategory, "category_id")
答案 0 :(得分:1)
Stack Overflow
错误。
产生此错误的代码通常通过执行无限递归来实现。如果您显示的代码是完整的lunchgenerate
函数,则在counter
或counter1
不为1的情况下,将lunchgenerate
再次调用具有完全相同的结果,再次,直到它完全耗尽堆栈上的空间并抛出异常。你需要有一些逃避逻辑来避免它。