私のコードに問題があります。私はユーザーの入力を検証しようとしているので、数値ではなく0であり、別の条件はdblFatInGramsはdblCaloriesInFoodより大きいことができないということです。私はこのステートメントを自分のコードに追加すると、残りのコードを実行せずにelseステートメントにまっすぐ進んでいます。Visual Basic IFステートメント
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Const intCaloriesPerGramoOfFat As Integer = 9 '9 calories per gram of fat
Const dblLowFoodPercent As Double = 0.3 'low fat food are less then 30 %
Dim dblCaloriesInFood As Double
Dim dblFatInGrams As Double
Dim intFatCalories As Integer
Dim dblTotal As Double
' Validating user input and show message in lable box
If (Double.TryParse(txtFoodCalories.Text, dblLowFoodPercent) And IsNumeric(txtFoodCalories.Text) And dblLowFoodPercent >= 0) Then
If (Double.TryParse(txtFatGrams.Text, dblLowFoodPercent) And IsNumeric(txtFatGrams.Text) And dblLowFoodPercent >= 0) And dblCaloriesInFood < dblFatInGrams Then
' User input
dblCaloriesInFood = CDbl(txtFoodCalories.Text)
dblFatInGrams = CDbl(txtFatGrams.Text)
'Calculate fat
intFatCalories = dblFatInGrams * intCaloriesPerGramoOfFat
' Calculate and dispaly % of cal. from fat
dblTotal = intFatCalories/dblCaloriesInFood
' Dispaly results
' Check if fat percentage is grater or equal to 30% and prints out results
If dblTotal <= dblLowFoodPercent Then
lblUserMessage.Text = "Low fat food"
lblTotal.Text = dblTotal.ToString("P")
Else
lblUserMessage.Text = "High fat food"
lblTotal.Text = dblTotal.ToString("P")
End If
Else
lblUserMessage.Text = "Enter a number of fat. Not grater than number of the calories and greater than 0"
End If
Else
lblUserMessage.Text = "Enter the number of calories. Greater than 0 "
End If
End Sub
私は、コンパイラは評価が左から右にされていることを保証しないだろう。したがって、変数dblLowFoodPercentは必要な前にTryParseによって記入されません。 "and"の代わりに "AndAlso"を使ってみてください。それはうまくいくかもしれませんが、それは素晴らしい解決策ではありません。 TryParseの値を必要とする前に、TryParseを短く呼び出します。私はこのことがどうなるかに非常に興味があります。 –
問題は 'Double.TryParse()'ステートメントが 'dblLowFoodPercent'で動作していることです。これはおそらくあなたが望むものではありません。 – Icemanind
'TryParse'ステートメントをチェックします。両方とも同じ変数' dblLowFoodPercent'に解析しています。また、正しいタグを入れてください。これはVBAではなくVB.netです。 –