Public Class Form2
Dim ss As Boolean
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i, z As Integer
ss = False
Butn_no.Focus()
While ss = False
Application.DoEvents()
i = Val(InputBox("enter 1st number", "program#3"
))
z = Val(InputBox("enter 2nd number", "program#3"))
If z = 0 Or i = 0 Then
MsgBox("one of the given number is empty try again or not integer", vbCritical, "error")
Else
If z = i * i Then
MsgBox("second number is the sqaure of first number", vbInformation, "program#3")
Else
MsgBox("second number is not the square of first" & vbNewLine & " first number = " & i.ToString & " 2nd number = " & z.ToString, MsgBoxStyle.OkCancel, "program#3")
End If
End If
End While
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Butn_no.Click
ss = True
End Sub
End Class
This is working but next time when while executed I am unable to click on button 2 due to input box which is showing at the top, with this same method I stopped the loop which is appending text in textbox in my earlier program. I just want to stop loop execution on button pressed if anyone?
Val returns a double and you have declared i as an integer. Same problem with z. Val is an old VB6 method. .Net has new methods to replace it. I used Integer.TryParse. If an non integer is entered it will not update the output variable which will remain 0. If the input is a valid Integer, i and z will be assigned the new value.
The Continue While takes the execution back to the top of the While.
Put your exit question in the loop. You can use Return to exit the Sub.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i, z As Integer
While True
Integer.TryParse(InputBox("enter 1st number", "program#3"), i)
Integer.TryParse(InputBox("enter 2nd number", "program#3"), z)
If z = 0 Or i = 0 Then
MsgBox("one of the given number is empty try again or not integer", vbCritical, "error")
Continue While
Else
If z = i * i Then
MsgBox("second number is the sqaure of first number", vbInformation, "program#3")
Else
MsgBox("second number is not the square of first" & vbNewLine & " first number = " & i.ToString & " 2nd number = " & z.ToString, MsgBoxStyle.OkCancel, "program#3")
End If
End If
Dim Answer = DialogResult.Yes
If Answer = MessageBox.Show("Do you want to quit?", "Quit?", MessageBoxButtons.YesNo) Then
Return
End If
End While
End Sub
Related
sorry I'm a newbie and I'm trying to write a program to get ten integers from user with a an Inputbox or Textbox and displays the biggest and lowest one in a label with visual basic. I'll be appreciated if you help me out with this.
Thank you. this is my solution. I don't know how to compare these ten numbers with each other.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers
Max = 0
i = 1
While (i <= 10)
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers
i = i + 1
End While
lblresult.Text = Container
End Sub
conceptually speaking you should use a List(Of Integer) or List(Of Double), perform the loop 10 times adding the value into the list.
Suppose this is our list
Dim container As New List(Of Integer)
To get input
Dim userInput = ""
Dim input As Integer
userInput = InputBox("please enter a number", "Enter a number")
If Integer.TryParse(userInput, input) Then
container.Add(input)
End If
After the loop
Console.WriteLine($"Min: {container.Min()} Max: {container.Max()}")
Does this make sense to you ?
Edit, based on asking for Windows Forms example.
You could do the following instead of a InputBox, requires a label, a button and a TextBox.
Public Class MainForm
Private container As New List(Of Integer)
Private Sub CurrentInputTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles CurrentInputTextBox.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CurrentLabel.Text = "Enter number 1"
End Sub
Private Sub ContinueButton_Click(sender As Object, e As EventArgs) _
Handles ContinueButton.Click
If Not String.IsNullOrWhiteSpace(CurrentInputTextBox.Text) Then
container.Add(CInt(CurrentInputTextBox.Text))
CurrentLabel.Text = $"Enter number {container.Count + 1}"
If container.Count = 10 Then
ContinueButton.Enabled = False
CurrentLabel.Text =
$"Count: {container.Count} " &
$"Max: {container.Max()} " &
$"Min: {container.Min()}"
Else
ActiveControl = CurrentInputTextBox
CurrentInputTextBox.Text = ""
End If
End If
End Sub
End Class
I really didn't want to do your homework for you but I was afraid you might be hopelesly confused.
First let's go over your code. See comments
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers 'Don't declare variables without an As clause
Max = 0 'Max is an object
i = 1 'i is and object
While i <= 10 'the parenthesis are unnecessary. You can't use <= 2 with an object
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers 'Container is an object; you can't use & with an object
i = i + 1 'Again with the object i can't use +
End While
lblresult.Text = Container
End Sub
Now my approach.
I created a List(Of T) at the Form level so it can be seen from different procedures. The T stands for type. I could be a built in type or type you create by creating a Class.
The first click event fills the list with the inputted numbers. I used .TryParse to test if the input is a correct value. The first parameter is a string; the input from the user. The second parameter is a variable to hold the converted string. .TryParse is very clever. It returns True or False base on whether the input string can be converted to the correct type and it fills the second parameter with the converted value.
The second click event loops through the list building a string to display in Label1. Then we use methods available to List(Of T) to get the numbers you desire.
Private NumbersList As New List(Of Integer)
Private Sub FillNumberList_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
While i < 10
Dim input = InputBox("Please enter a whole number")
Dim inputInt As Integer
If Integer.TryParse(input, inputInt) Then
NumbersList.Add(inputInt)
i += 1 'We only increment i if the parse is succesful
End If
End While
MessageBox.Show("Finished Input")
End Sub
Private Sub DisplayResults_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Text = "You input these numbers "
For Each num In NumbersList
Label1.Text &= $"{num}, "
Next
Label2.Text = $"The largest number is {NumbersList.Max}"
Label3.Text = $"The smallest number is {NumbersList.Min}"
End Sub
I am trying to insert a numbered bullet list when a user selects the button it will increment the counter
I have searched questions online and different types of loop condition statements
Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click
ToolStripButton16.CheckOnClick = False
Dim i As Integer
i = 0
Dim numbList As String
Dim buttonClickCount As Integer
buttonClickCount = 0
Do While (i = buttonClickCount)
i += 1
numbList = " " & i & "." & vbCrLf
RichTextBox1.AppendText(numbList)
Loop
buttonClickCount += 1
End Sub
Expected result:
1.
2.
3.
4.
Probably not the most elegant solution but it should put you in the right direction.
'Using a class variable here allows you to keep an "application state".
Dim buttonClickCount as Integer = 0
Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click
ToolStripButton16.CheckOnClick = False
buttonClickCount += 1
Dim newValue As String = " " & buttonClickCount & "." & vbCrLf
RichTextBox1.AppendText(newValue)
End Sub
My program works when I input the number but when I backspace it to enter another number it shows an error.
Public Class Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim calculate = 100
Label1.Text = "The calculation is " & (TextBox1.Text * calculate)
End Sub
End Class
Before your calculation you have to check that TextBox1.Text <> "".
If TextBox1.Text <> "" Then
Label1.Text = "The calculation is " & (TextBox1.Text * 100)
Else
Label1.Text = "no value"
End If
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 the proper place to place my loop. I am trying to do a while loop, but when I try it allows me to enter the 7 innings, but once I do it is an infinate loop with the message only seven innings are allowed and it does not display the lblTotal. It works without the loop, but it just doesnt allow me to enter all of the innings back to back. I would really appreciate if you could help me. I feel like I placed the loop in the wrong place.
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
Do While runs <= 7
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
Loop
'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
Private Sub mnuClear_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 mnuExit_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class
Do While runs <= 7
'runs' variable should be updated (adding +1) within the 'Do While' loop in order to be able to satisfy the condition and break out.
(...)
runs += 1
Loop
I have been struggling with this code for a while. I'm trying to make it so after the user gets the number right, the program counts how many tries it has taken them to get the number right. How can I do this?
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
'SELECTS THE SECTET NUMBER
Randomize() 'WITHOUT rANDOMIZE, THE SAME SEQUENCE OF NUMBERS APPEARS EACH RUN
secretNumber = Int(Rnd(1) * 1000 + 1) 'picks a random nubmer between 1 and 1000
'sets the initial prompts
Me.lblLow.Text = 1
Me.lblHigh.Text = 1000
Me.txtGuess.Focus()
Dim count As Integer
btnEnterGuess.Enabled = True
btnStart.Enabled = False
Dim i As Integer
For i = 1 To count
count = count + 1
Next i
Do
count = count + 1
Loop Until count = secretNumber
MessageBox.Show("It took you " & i - 1 & " tries to get the number correct.")
End Sub
I threw this piece of code togeather, hopefully it will help.
Something to note when writing this kinda code, is that all this code is running on a single thread (unless you declare it otherwise). This means your program will become unresponsive when you run that for loop.
Public Class Form1
Dim count As Integer = 0
Dim answer As Integer = 0
Dim GameRunning As Boolean = True
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message,
ByVal keyData As System.Windows.Forms.Keys) _
As Boolean
'Gets all keystrokes on the fourm
If GameRunning Then
'converts keystroke to key ID and tests to see if the keystroke is the ENTER key
If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
'try catch to prevent crash if text in entered
Try
If txtAnswer.Text = answer Then
MessageBox.Show("Congratz! It took you " & count & " tries to guess the number!")
Else
txtAnswer.Text = ""
count = (count + 1)
End If
Catch ex As Exception
End Try
End If
End If
'update label to show tries
lblTries.Text = "Tries: " & count
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Private Sub SetupOnLoad() Handles MyBase.Load
Reset()
End Sub
Public Sub Reset()
count = 0
Randomize()
answer = Int(Rnd(1) * 1000 + 1)
txtAnswer.Text = ""
lblTries.Text = "Tries: " & count
GameRunning = True
End Sub
'the Reset() code is ran on the program launch and when you press the button to prepare the game.
Private Sub Reset_Game() Handles BtnReset.Click
Reset()
End Sub
End Class
This code gets the user input in the text box. When the user presses ENTER, the program tests to see if its the correct number.
Hope this helped!
I will try something like this, randomize need to be placed outside of the click
Public Class Form1
Dim count As Integer = 0
Dim answer As Integer = 0
Private Sub btnStart_ClicK(sender As Object, e As EventArgs) Handles btnStart.Click
Randomize()
answer = Int(Rnd(1) * 1000 + 1)
btnStart.Enabled = False
btnGuess.Enabled = True
End Sub
Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click
count += 1
If answer = TextBox1.Text Then
MessageBox.Show("It took you " & count & " tries to get the number correct.")
btnStart.Enabled = True
btnGuess.Enabled = False
count = 0
answer = 0
Else
TextBox1.Text = ""
End If
End Sub
End Class