Recently I have been tasked with making a calculator in VB. It must include stuff like logic or denary/binary/hex conversions. When I was making the binary->denary conversion I encountered a thing where an if statement checking if the inputted number is binary always returned true and activated. Here is the code for the binary conversion system: (please forgive me for the goto's)
Private Sub bbin_Click(sender As Object, e As EventArgs) Handles bbin.Click
If temp = IsNumeric(inputbox.Text) Then
MessageBox.Show("Value Not Numeric", "ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
Else
For i = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, i, 1) <> "0" Or Mid(inputbox.Text, i, 1) <> "1" Then
MessageBox.Show("Value Not Binary", "ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
GoTo skipbin
End If
Next
For x = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, x, 1) = "1" Then
decnum = decnum + 2 ^ (Len(inputbox.Text) - (x - 1))
End If
Next
binnum = inputbox.Text
inputbox.Text = ""
End If
textbox.Text = "Dec = " + decnum.ToString + " Bin = " + binnum.ToString + " Hex = " + hexnum.ToString
skipbin:
End Sub
Let me explain:
The inputbox is the place where the user can input the numbers/operations. The first If checks if the value inputed is a number.
Then a check is ran to ensure the number is binary. (this is where im having problems)
The conversion is ran. It doesn't work as intended at the moment, but I'm sure I'll get it working.
Then the binary and denary values get displayed in a second textbox that I use to display the answers.
The problem I'm having is only with this section: (again, forgive me for the goto functions)
For i = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, i, 1) <> "0" Or Mid(inputbox.Text, i, 1) <> "1" Then
MessageBox.Show("Value Not Binary", "I AM ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
GoTo skipbin
End If
Next
It's supposed to check each digit if it's a 1 or a 0, and if not, it displays an error and skips the conversion.
What do I need to change to make the input validation work as intended?
You need And instead of Or.
When you get a bit of code that you can't figure out why it doesn't work, it is often a good idea to make the minimal bit of code that shows the problem - removing everything else can often lead you to the problem.
In this case, to confirm my answer was correct, I used this:
Option Infer On
Option Strict On
Module Module1
Sub Main()
Dim s = "000012"
For i = 1 To Len(s)
Dim c = Mid(s, i, 1)
If c <> "0" And c <> "1" Then
Console.WriteLine("Value Not Binary: {0}", c)
End If
Next
Console.ReadLine()
End Sub
End Module
You can use AndAlso instead of And: it eliminates any unnecessary processing of the clauses (known as short-circuiting). Similarly, there is OrElse instead of Or.
Your problem is your condition result is always true for any binary number.
try this instead
Dim currentChar = CInt(Mid(InputBox.Text, i, 1))
If currentChar <> 0 And currentChar <> 1 Then
MessageBox.Show("Value Not Binary", "ERROR", MessageBoxButtons.OK)
InputBox.Text = ""
GoTo skipbin
End If
Related
I try to run this program but an error always appears:
Conversion from the string "LBLBuku" to type' Double 'is not valid.
If LBLBuku.Text >= 5 Or Val(LBLBuku.Text) + Val(TextBox1.Text) > 5 Then
MsgBox("Peminjaman Melebihi")
Else
If lbljudul.Text = "" Or TextBox1.Text = "" Then
MsgBox("Silahkan isi Kode Buku")
Else
DataGridView1.Rows.Add(New String() {TextBox2.Text, lbljudul.Text, LBLPengarang.Text, LBLTahun.Text, TextBox2.Text})
TextBox1.Text = ""
TextBox2.Text = ""
lbljudul.Text = ""
TextBox2.Text = ""
LBLPengarang.Text = ""
LBLTahun.Text = ""
Call rumustotalbuku()
End If
End If
Notice on your code the line
LBLBuku.Text >= 5
The property Text is of type String, you would have to convert the text to an integer type first before you can use ">=".
First I declare a variable to hold the integer value in the Text Box. Integer.TryParse will return true if it can convert the string in the text box to an integer. It will also fill the variable intTB1 with the number.
I am assuming that LBLBuku is a label so the .Text property has been set from code. We can depend on this being a number so all we need to do is the conversion with CInt(). We can use the variable we got from the .TryParse in the Or CInt(LBLBuku.Text) + intTB1 > 5 instead of referring to the text box again.
We don't need to check if TextBox1 is empty because it wouldn't have passed the .TryParse if it was.
Last and probably least, you don't need the Call keyword in most situations.
You do realize that you have added TextBox2 twice to the new DataRow.
Private Sub OPCode()
Dim intTB1 As Integer
If Not Integer.TryParse(TextBox1.Text, intTB1) Then
MessageBox.Show("Please enter a number in TextBox1.")
Return
End If
If CInt(LBLBuku.Text) >= 5 Or CInt(LBLBuku.Text) + intTB1 > 5 Then
MsgBox("Peminjaman Melebihi Maksimal")
Else
If lbljudul.Text = "" Then
MsgBox("Silahkan isi Kode Buku")
Else
DataGridView1.Rows.Add(New String() {TextBox2.Text, lbljudul.Text, LBLPengarang.Text, LBLTahun.Text, TextBox2.Text})
TextBox1.Text = ""
TextBox2.Text = ""
bljudul.Text = ""
TextBox2.Text = ""
LBLPengarang.Text = ""
LBLTahun.Text = ""
rumustotalbuku()
End If
End If
End Sub
I am a new programmer learning Visual Basic.
Right now, I'm working on a project about a softball scoreboard. I have been working on this project for a bit, and I am confused on 1 thing.
The thing I am confused on is that I put in a messagebox that said invalid input for negative numbers, but it does not delete it from lstScores and even though the message box appears it still counts as a inning input.
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
This is the code:
Public Class frmSoftballScoreboard
Const VALID_MESSAGE As String = "Enter valid runs value"
Const ONLY_MESSAGE As String = "Only seven innings are allowed"
'Declaring array
Dim scores(6) As Double
'declaring variables
Dim runs As String
Dim runningScore As Integer = 0
Dim i As Integer = 0
Dim out As Double
'page load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstScores.Items.Add("Runs : Running Score")
End Sub
'Enter score button
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
'Clear Menu click
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
lstScores.Items.Clear()
lblTotal.Text = ""
'reset i to 0
i = 0
End Sub
'Exit Menu click
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class
I would really appreciate it if you could help. Thank you.
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
Exit Sub
ElseIf runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
This is the reason why if you input invalid data it will add into lstScores, because your If statement.. is in bottom of your code, although is not recommend where you put the If else statement... Remember reading of the code is start in top to bottom.
Your first If statement is like this. If runs <> "" then ...., of course if you type the -1 value in the Input Text the Boolean will result to true, If -1 <> "" = true, then it will proceed to the statement which is
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
This is the line of code even the value is invalid or not it still adding value in the lstScores, lstScores.Items.Add(scores(i) & " :" & runningScore)
Now after that statement you will receive a message which is :
Enter valid runs value
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
That code is the reason why you receiving the message. If you input -1 of course the result of boolean is true, why? -1 is lessthan to 0 which is true.
The thing i do is, I've insert If statement.. above, which is If runs < 0 then .... and also Exit Sub to instantly end the statement. If you input -1 to Input Text the result is something like this, if runs(-1) lessthan to 0 the Boolean result is true then it will proceed to statement which is the Message and Exit Sub.
Try my code above, and also use Breakpoints.. Hope this helps..
I am working on a Budget calculator for a class project. Basically everything works great except one little annoying nuance.
When you don't enter a number or you enter a negative number you get an error message. However, when you accidentally type in a letter, get the error, then type in the negative number it just exits, and I want it to show that error and loop back until they enter in a positive number.
I am using VBA in Visual Studio 2012, this is a Windows Form Application.
Dim strEntertainmentHeading As String = "Entertainment Expenses"
Dim strHeading As String = "Budget Alottment"
Dim strNonNumericError As String = "Error - Enter a number for the Expense"
Dim strNegativeError As String = "Error - Enter a positive number for the Expense"
Dim strEntertainmentInput As String = "Enter the amount for Entertainment Expenses"
Dim strEntertainment As String
Dim decEntertainment As Decimal
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
Do
If strEntertainment = "" Then
Exit Sub
ElseIf IsNumeric(strEntertainment) Then
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment >= 0 Then
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
' Display error message if user entered a negative value
Else
strEntertainmentInput = strNegativeError
End If
Else
strEntertainmentInput = strNonNumericError
End If
If decEntertainment <= 0 Then
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
End If
Loop Until IsNumeric(strEntertainment) And decEntertainment >= 0
Of course, you have this problem: decEntertainment is 0 by default and after asking for input the second time, you do not Convert.ToDecimal anymore.
You avoid this type of errors if you adopt a clear coding style, like
Do
strEntertainmentInput = ''
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
If Not IsNumeric(strEntertainment) Then
strEntertainmentInput = strNonNumericError
Else
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment < 0 Then
strEntertainmentInput = strNegativeError
Else
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
End
End
Loop Until strEntertainmentInput = ''
How can I multi validate a text box? I only want the user to input integer but the integer shouldn't be 0 or less, how can I do this? This is what I've done:
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
If IsNumeric(txtCopies.Text) = False Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
blabla
End If
End If
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
End If
there you go, else please explain better
you can also do
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
if not(IsNumeric(txtCopies.Text) = True) then
ErrorProvider1.SetError(txtCopies, "Numbers Only")
else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
end if
End If
It's been a long time since I've done VB but here you go:
It has to be able to convert whatever is in the text box to an integer.
to do this, it checks if the string is numeric, if it is, then the num variable takes its value (so it can be checked). If this value is greater than 0 then it says it's not valid.
It needs to be a nested If statement for this to happen.
Sub OnClick()
Dim str As String
Dim num As Integer
str = TextBox1.Text
If IsNumeric(str) Then
num = str
If num <= 0 Then
TextBox1.Text = "Sorry, not valid"
End If
Else
TextBox1.Text = "Sorry, not a number"
End If
End Sub
Dim intValue As Integer
If Not Integer.TryParse(TxtBox.Text, intValue) OrElse intValue < 0 Then
Else
End If
In your style ..
If Not IsNumeric(txtCopies.Text) And Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
Else
'Blabla
End If
End If
If interger. Parse(hours Text box. Tex)<=10 then
' code to perform calculation
Else
Message box.Show("Two many hours."," Invalid Data",MessageBoxButtons.OK)
End if
I am doing my homework for my visual basic class. I have most of the code written and everything seems to be working well except for my If Not statement that catches the exception when the loop does not find what it is looking for. Anyone see a problem with the way the code looks. The file is loaded in using the browse button already and it works find when I enter information that the loop can find.
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles btnSearch.Click
'event level variables
Dim Found As Boolean
Dim Counter As Integer
'looks for entry match
If rdoAbbrev.Checked = True Then
Do Until Found Or Counter > 257
If Country(Counter).Abbreviation.ToUpper = txtAbbrev.Text.ToUpper Then
Found = True
txtCountry.Text = Country(Counter).Names
Else
Counter += 1
End If
Loop
Else
Do Until Found Or Counter > 257
If Country(Counter).Names.ToUpper = txtCountry.Text.ToUpper Then
Found = True
txtAbbrev.Text = Country(Counter).Abbreviation
Else
Counter += 1
End If
Loop
If Not Found Then
MessageBox.Show("This is not a valid entry.", "NO MATCH FOUND", MessageBoxButtons.OK)
If rdoAbbrev.Checked = True Then
txtAbbrev.Text = ""
txtAbbrev.Focus()
Else
txtCountry.Text = ""
txtCountry.Focus()
End If
End If
End If
'match not found response
'reset variables
Counter = 0
Found = False
End Sub
You If Not Found block only occurs if rdoAbbrev.Checked = True. Is that what you intended? If not, then that block of code should either be located outside of the first If block (below it) or you should have a second If block after the first While loop.
EDIT
It looks like Country is an array. You should probably use Counter >= Country.Length.
Arrays in VB.NET are 0-based. Meaning that the first item is located at Country(0), the second item is at Country(1), etc. If there are 100 elements in the array, then the last element is located at Country(99). Country(100) does not exist and will cause an Exception if you try to access it.
I'm not sure what the requirements of your homework are, but usually to iterate over the elements of a collection (array, list, etc), you would use a For loop. You can jettison from the loop early with the Exit command.
For Counter As Integer = 0 To Country.Length - 1
'...Country(Counter)
If Found Then Exit For
Next
Assuming you want the "Not Found" part to execute regardless of the rdoAbbrev.Checked property, it looks like a slight error in your logic (easily fixed).
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
'event level variables
Dim Found As Boolean
Dim Counter As Integer
'looks for entry match
If rdoAbbrev.Checked = True Then
Do Until Found Or Counter > 257
If Country(Counter).Abbreviation.ToUpper = txtAbbrev.Text.ToUpper Then
Found = True
txtCountry.Text = Country(Counter).Names
Else
Counter += 1
End If
'You could also write this as:
'Found = Country(Counter).Abbreviation.ToUpper = txtAbbrev.Text.ToUpper
'If Found Then
' txtCountry.Text = Country(Counter).Names
'Else
' Counter += 1
'End If
Loop
Else
Do Until Found Or Counter > 257
If Country(Counter).Names.ToUpper = txtCountry.Text.ToUpper Then
Found = True
txtAbbrev.Text = Country(Counter).Abbreviation
Else
Counter += 1
End If
'You could also write this as:
'Found = Country(Counter).Names.ToUpper = txtCountry.Text.ToUpper
'If Found Then
' txtAbbrev.Text = Country(Counter).Abbreviation
'Else
' Counter += 1
'End If
Loop
End If
'match not found response
'Move your "Not Found" here so that the not found works regardless of the rdoAbbrev.Checked property.
If Not Found Then
MessageBox.Show("This is not a valid entry.", "NO MATCH FOUND", MessageBoxButtons.OK)
If rdoAbbrev.Checked = True Then
txtAbbrev.Text = ""
txtAbbrev.Focus()
Else
txtCountry.Text = ""
txtCountry.Focus()
End If
End If
'reset variables
Counter = 0
Found = False
End Sub
Probably you should End the If statements within their range in the code and avoid ending all your If statements at the end of the code lines. usually works for me in Basic. I think that Basic has a lot of advantages, but for me it still not a high level language that has some problems because it is so easy to work with.