How can I get ten numbers and displays the biggest and lowest one? - vb.net

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

Related

Add a completely different line with every button click

Complete noob to vb.net (and programming in general) here, all I really want is every time I click a button, the number in the textbox is added by 1 but the new number shows up on the next line. Tried to google this a hundred times but nothing really helped.
I don't want to use loops as I don't want all numbers to show up at once, only for the added number to show up after clicking a specific button (on a new line).
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtoutput As String = ""
Dim a As Integer = 1
txtoutput &= "the value of a =" & a & Environment.NewLine
a = a + 1
TextBox1.Text = txtoutput
End Sub
You are replacing the Text, you want to append a new line, so you need to do:
Private a As Int32 = 0
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
a += 1
Dim newLine = $"the value of a = {a}"
TextBox1.Text = TextBox1.Text & Environment.NewLine & newLine
End Sub
You also have to use a field and not a local variable if you want to retain the old value and increment it. Otherwise it is reset always to it's inital value.
Please try to change dim a to static a
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtoutput As String = ""
Static a As Integer = 1
txtoutput &= "the value of a =" & a & Environment.NewLine
a = a + 1
TextBox1.Text = txtoutput
End Sub

How do I count how many guesses it takes to get the correct number in Visual Basic?

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

Why is it only displaying one result

This program is supposed to accept in valid candidates for voting, add the names typed in a text box to a list box. In the list box the user may double click on the candidate they choose. After the tally button is clicked a list box displaying the candidates' Names and votes will appear along side the other list box.
My problem is that the lstTallies only displays the last voted candidate.
Below is my code
Public Class Form1
Dim maxVotes As Integer
Dim winner As String
Dim votes() As Integer
Dim index As Integer
Dim candidates As String
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If Not isValidInput(txtNewCandidate.Text) Then
Exit Sub
End If
lstCandidates.Items.Add(txtNewCandidate.Text)
txtNewCandidate.Clear()
txtNewCandidate.Focus()
ReDim Preserve votes(index)
index += 1
End Sub
Private Function isValidInput(ByRef firstName As String) As Boolean
If IsNumeric(txtNewCandidate.Text) Or txtNewCandidate.Text = "" Then
MsgBox("Please input a valid candidate name.")
txtNewCandidate.Focus()
Return False
Else
Return True
End If
End Function
Private Sub btnTally_Click(sender As Object, e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
lstTallies.Items.Add(lstCandidates.Text & " " & votes(lstCandidates.SelectedIndex))
End Sub
Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
If lstCandidates.SelectedIndex = -1 Then
MsgBox("Select a candidate by double-clicking")
End If
votes(lstCandidates.SelectedIndex) += 1
MsgBox("Vote Tallied")
End Sub
End Class
Try this:
Assuming the index of the Candidate and his/her Vote are the same:
Private Sub btnTally_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
For i = 0 To lstCandidates.Items.Count - 1
lstTallies.Items.Add(lstCandidates.Items(i).ToString & " - " & votes(i))
Next
End Sub
You cannot get the contents of the ListBox unless you iterate it.

reading bits with for loop, I get 7 bits instead of 8, what's the wrong with this code

OutPuts:
TextBox 2 : FalseTrueTrueTrueTrueTrueFalseFalse
TextBox 3 : 1111100
My problem is why is that the first boolean of "TextBox 2" is "False" and the first integer of "TextBox 3" is 1 ? "TextBox 2" has 8 booleans while "TextBox 3" only has 7 bits. And apparently, in "TextBox 3, the first bit is not there. Where have I done wrong .. ? commentary has provided in the code. Please shed some light here.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim array() As Byte = File.ReadAllBytes("D:\binfile.bin")
Using memory As MemoryStream = New MemoryStream(array)
Using reader As BinaryReader = New BinaryReader(memory)
ba1 = New BitArray(array)
Dim bit_set As Integer
For i As Integer = 0 To 7
'to view all 8 bits in boolean format
TextBox2.Text = TextBox2.Text & ba1.Get(i)
If ba1.Get(i) = False Then
boolean2bits = 0
'End If
ElseIf ba1.Get(i) = True Then
boolean2bits = 1
End If
'to collect all 8 bits in integer format
bit_set = bit_set & boolean2bits
If (i = 7) Then
Exit For
End If
Next
'to view collected bits in the text box
TextBox3.Text = bit_set
End Using
End Using
End Sub
Simply because you are assigning the value 01111100 to the integer variable bit_set. But of course, as an integer, that leading 0 is not significant, so it gets stripped out automatically, and gets simplified to simply 1111100, because it is the same number after all.
If you don't want to lose the leading zero for display purposes, then you probably don't want bit_set to be of type Integer. Just declare at as a Dim bit_set As String, and the leading zero will not disappear.
Looks like you're making some progress towards your end goal Pretty_Girl.
Here are some snippets to take in and digest:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ba1 = New BitArray(File.ReadAllBytes("D:\binfile.bin"))
Dim bits As New List(Of String)
Dim bools As New List(Of String)
For i As Integer = 0 To 7
bools.Add(ba1.Get(i).ToString)
bits.Add(If(ba1.Get(i), "1", "0"))
Next
'to view collected bits/bools in the text box
TextBox2.Text = String.Join(",", bools.ToArray)
TextBox3.Text = String.Join("", bits.ToArray)
End Sub
Alternate Version 2:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ba1 = New BitArray(File.ReadAllBytes("D:\binfile.bin"))
TextBox2.Clear()
TextBox3.Clear()
For i As Integer = 0 To 7
TextBox2.AppendText(ba1.Get(i).ToString & ",")
TextBox3.AppendText(If(ba1.Get(i), "1", "0"))
Next
End Sub
Alternate Version 3:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ba1 = New BitArray(File.ReadAllBytes("D:\binfile.bin"))
Dim bits As New System.Text.StringBuilder
Dim bools As New System.Text.StringBuilder
For i As Integer = 0 To 7
bools.Append(ba1.Get(i).ToString & ",")
bits.Append(If(ba1.Get(i), "1", "0"))
Next
TextBox2.Text = bools.ToString
TextBox3.Text = bits.ToString
End Sub

Random Numbers to Text in Label

Public Class MainForm
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub guestsTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles guestsTextBox.KeyPress
' allows only numbers and the Backspace key
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'fills the list box and selects the first item
typeListBox.Items.Add("Kid's Birthday")
typeListBox.Items.Add("21st Birthday")
typeListBox.Items.Add("40th Birthday")
typeListBox.Items.Add("Other Birthday")
typeListBox.SelectedIndex = 0
End Sub
Private Sub calcButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles calcButton.Click
'displays the total charge
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Integer.TryParse(guestsTextBox.Text, guests)
typeIndex = typeListBox.SelectedIndex
'determine the price per guest
Select Case typeIndex
Case 0 'Kid's Birthday
guestPrice = 11
Case 1 '21st Birthday
guestPrice = 20
Case 2 '40th Birthday
guestPrice = 25
Case Else 'other birthdays
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
totalLabel.Text = totalCharge.ToString("C0")
End Sub
Private Sub testDataButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles testDataButton.Click
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Dim randomGen As New Random
Dim setCounter As Integer = 1
testDataLabel.Text = String.Empty
Do
guests = randomGen.Next(1, 51)
typeIndex = randomGen.Next(0, 4)
For Each I As Object In typeListBox.SelectedItems
testDataLabel.Text += I.ToString() & ControlChars.NewLine
Next
'determine the price per guest
Select Case typeListBox.SelectedIndex
Case 0
guestPrice = 11
Case 1
guestPrice = 20
Case 2
guestPrice = 25
Case Else
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
testDataLabel.Text = testDataLabel.Text &
typeIndex.ToString & " " &
guests.ToString & " " &
totalCharge.ToString("C0") &
ControlChars.NewLine
setCounter += 1
Loop Until setCounter > 10
End Sub
Private Sub typeListBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles typeListBox.SelectedIndexChanged
End Sub
End Class
When I click on a button named "Generate Test Data" It generates a list of random numbers in a label. I want these numbers to say the type of birthday instead of the number.
0 being "Kid's Birthday"
1 being "21st Birthday"
2 being "40th Birthday"
and 3 being "Other Birthday"
How would I go about doing this?
Any help would be much appreciated!
If I understood your question correctly, you can declare an enum and have a dictionary of that enum to String.
The Enum takes care of dealing with numbers in code, and rather use human readable constructs. Dictionary will make sure your users will also see human readable constructs.
Please see below code (needs a brand new WinForms project and a ListBox called ListBox1 on the main form):
Option Strict On
Public Class Form1
'Declare this enum to avoid dealing with naked numbers in code
Enum BirthdayTypes
btKids = 0
bt21st = 1
bt40th = 2
btOther = 3
End Enum
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
'Suppose your input value is a number,
'but you don't want to deal with numbers
Dim typeIndex As Integer = 2
'You can convert your number to BirthdayTypes,
'making your input "correct"
Dim typeIndexBt As BirthdayTypes = ConvertBirthdayIndexToType(typeIndex)
'Calculation of guest price is now "human readable"
Dim guestPrice As Integer = CalculateGuestPrice(typeIndexBt)
'You can create a dictionary for diplaying the values
Dim displayDictionary As New Dictionary(Of BirthdayTypes, String)
With displayDictionary
.Add(BirthdayTypes.btKids, "Kid's Birthday")
.Add(BirthdayTypes.bt21st, "21st Birthday")
.Add(BirthdayTypes.bt40th, "40th Birthday")
.Add(BirthdayTypes.btOther, "Other Birthday")
End With
'Here is how you would those values into a ListBox
With ListBox1
.DataSource = displayDictionary.ToList
.ValueMember = "Key"
.DisplayMember = "Value"
End With
'Now your ListBox displays strings,
'but SelectedValue would return an object of type BirthdayTypes
'You can extract random values from the above dictionary by index,
'and create a new list from it
Debug.WriteLine(ListBox1.SelectedValue) 'outputs btKids
End Sub
Private Function CalculateGuestPrice(bt As BirthdayTypes) As Integer
Select Case bt
Case BirthdayTypes.btKids : Return 11
Case BirthdayTypes.bt21st : Return 20
Case BirthdayTypes.bt40th : Return 25
Case BirthdayTypes.btOther : Return 15
End Select
'should never here
Throw New Exception("Unknown birthday type")
End Function
Private Function ConvertBirthdayIndexToType(index As Integer) As BirthdayTypes
If index < 3 Then Return CType(index, BirthdayTypes)
Return BirthdayTypes.btOther
End Function
End Class
Disclaimer: this code is just a demo of what can be done, not meant to be used a complete solution.
I would use a string.
Dim thestring() As String = {"Kid's Birthday", _
"21st Birthday", _
"40th Birthday", _
"Other Birthday"}
Now each of those numbers will represent the text in thestring.
thestring(0) = kids birthday
thestring(1) = 21 birthday
thestring(2) = 40th birthday
thestring(3) = other birthday
Make sense? I would help further, but i don't quite get what you are trying to do.