visual basic looping issue - vb.net

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

Related

How can I get ten numbers and displays the biggest and lowest one?

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

Repeat the task using while loop until user clicks on “No” button?

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

How to find and highlight next instance of word in richtextbox in visual basic?

Here is the visual basic windows application form I am currently working on.
https://i.snag.gy/EzoXr3.jpg
How can I write code for the find next button like in this video.
https://www.dropbox.com/s/u93h9jn605uhwsu/CPT341Project2Walkthrough.avi?dl=0
If I can get a syntax to store a index variable outside the private sub of findnext button, I can solve the problem. Because everytime I click the findnext button, I have to find the respective instance of that word in the filetext. Or I can apply some code to find it in the substring of remaining text after its first occurrence.
Below is my code:
Public Class Form1
'Enter your name
'Date
'Class - CPT 341 VB.NET NJIT
Private Sub openBtn_Click(sender As Object, e As EventArgs) Handles openBtn.Click
If OpenFileDialog.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
fileText.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog.FileName)
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Bring the form to the inital state for a different search
Dim temp As String = fileText.Text
fileText.Text = temp
outputIndex.ForeColor = Color.Black
'MessageBox to show error for empty search textbox
If inputText.Text = "" Then
MessageBox.Show("Enter Text to Search", "CPT 341 Fall 2018 - Project 2")
Else
'Declare variables
Dim txt As String : Dim x As Integer = 0 : Dim output As String
txt = inputText.Text
If fileText.Text.IndexOf(txt) <> -1 Then
Dim idx As Integer = CStr(fileText.Text.IndexOf(txt))
outputIndex.Text = idx
'Find and highlight the first word searched in the RichTextBox
fileText.Find(txt, x, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
'populate the string with ANSI numbers
output = Asc(txt(0))
For x = 1 To (txt.Length - 1)
output = output & " " & Asc(txt(x))
Next x
outputANSI.Text = output
ElseIf fileText.Text = "" Then
MessageBox.Show("Please open a file to search from", "CPT 341 Fall 2018 - Project 2")
Else
outputIndex.Text = txt & " is not found"
'Bring the form to inital state
fileText.Text = temp
'Change the index textbox text color to red
outputIndex.ForeColor = Color.Red
'Empty the ANSI textbox
outputANSI.Text = ""
End If
End If
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim txt As String = inputText.Text
Dim Index As Integer = fileText.Text.IndexOf(txt) + txt.Length
'Find and highlight the word searched in the RichTextBox other than first occurrence
fileText.Find(txt, Index, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
Index = fileText.Text.IndexOf(txt, Index) + txt.Length + 1
End Sub
Private Sub btnWords_Click(sender As Object, e As EventArgs) Handles btnWords.Click
wordCount.Text = fileText.Text.Split(" ").Length
End Sub
Private Sub btnChars_Click(sender As Object, e As EventArgs) Handles btnChars.Click
charCount.Text = fileText.Text.Length
End Sub
End Class
Or any other suggestion would be helpful.

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

VB.NET Read text file line by line and set every line in textbox with button clicks

hello i want to read text file line by line and set every lien in textbox eash time i click the button
this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Static count As Integer
count = count + 1
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
Dim readLines() As String = IO.File.ReadAllLines(myFile)
If count = 1 Then
TextBox1.Text = readLines(0)
End If
If count = 2 Then
TextBox1.Text = readLines(1)
End If
If count = 3 Then
TextBox1.Text = readLines(2)
End If
If count = 4 Then
TextBox1.Text = readLines(3)
End If
If count = 5 Then
TextBox1.Text = readLines(4)
End If
If count = 6 Then
TextBox1.Text = readLines(5)
End If
End If
End Sub
I think you need to read the file just one time when you load your form (assuming a WinForms example here)
' Declare these two globally
Dim readLines() As String
Dim count As Integer = 0
Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load
' In form load, read the file, just one time
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
readLines() As String = IO.File.ReadAllLines(myFile)
else
TextBox1.Text "File not found"
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Check if you have a file and if you don't have reached the last line
if readLines IsNot Nothing AndAlso count < readLines.Length Then
TextBox1.Text = readLines(count)
count += 1
else
TextBox1.Text "End of file"
End If
End Sub
This reduces the amount of code you need to write:
TextBox1.Text = readLines(count - 1)