Word and vowel count in VB 2017 - vb.net

I need to program a simple console application that takes an input string and then calls a sub routine to figure out the amount of words and the amount of vowels in the string. I've written this and for some reason it doesn't output the text I put in the Console.Writeline code. Any help on how to do this?
Module Module1
Sub Main()
Dim Sentence As String
Console.WriteLine("Sentence Analysis")
Console.WriteLine()
Console.WriteLine("Enter a sentence then press 'Enter'")
Console.WriteLine()
Sentence = Console.ReadLine()
Sentence = Sentence.ToUpper
Call Words(Sentence)
Call Vowels(Sentence)
Console.ReadLine()
End Sub
Sub Words(ByVal Input As String)
Dim Count As Integer
Dim Index As Short
Dim Character As Char
Do Until Index = Len(Input)
Character = Input.Substring(Index)
If Character = " " Then
Count = Count + 1
End If
Loop
Console.WriteLine("Your sentence contains {0} words.", (Count))
End Sub
Sub Vowels(ByVal Input As String)
Dim Count As Integer
Dim Vowels() As String = {"A", "E", "I", "O", "U"}
Dim Index As Short
Dim Character As Char
Do Until Index = Len(Input)
Character = Input.Substring(Index)
If Character = Vowels(Index) Then
Count = +1
End If
Loop
Console.WriteLine("Your sentence contains {0} words.", (Count))
End Sub
End Module

In Words you have the following code:
Do Until Index = Len(Input)
Index is never incremented and so loops infinitely.
Same issue in Vowels as well

Is the following any help to you?
Rather than looking at whether a sentence contains vowels, it looks at whether a list of vowels contains each character in the sentence.
For the word count, it similarly asks whether a string containing a single space contains each character in the sentence (the "word count" in this case is just a count of spaces, so leading or trailing spaces, or extra spaces between words, will be counted as extra words, as your code currently does).
It also allows us to abolish the separate method calls, and the hand-rolled looping code which, as you can see, are prone to small bugs (and I personally would recommend using a For loop rather than Do Until loop in this kind of situation, because For loops are designed to increment the index automatically).
Sub Main()
Console.WriteLine("Sentence Analysis")
Console.WriteLine()
Console.WriteLine("Enter a sentence then press 'Enter'")
Console.WriteLine()
Dim sentence As String
sentence = Console.ReadLine()
Dim vowel_count As Integer = sentence.Count(Function(c) "aeiou".Contains(Char.ToLower(c)))
Dim word_count As Integer = sentence.Count(Function(c) " ".Contains(Char.ToLower(c)))
Console.WriteLine("Your sentence contains {0} words.", word_count)
Console.WriteLine("Your sentence contains {0} vowels.", vowel_count)
Console.ReadLine()
End Sub

You go to the same college as I did. Here is the code...
Option Compare Text
Imports System
Imports System.Diagnostics.Metrics
Imports System.Reflection
Imports System.Text.RegularExpressions
Module Program
Sub Main(args As String())
Console.WriteLine("Sentence Analysis")
Console.WriteLine()
Console.WriteLine("Enter a sentence, then press 'Enter'")
Console.WriteLine()
Dim input As String = Console.ReadLine
Dim letterbyletter() As Char = input.ToCharArray
Dim counter As Integer = 1
Dim vowelcounter As Integer
Call wordcount(input, letterbyletter, counter)
Console.WriteLine("Your sentence contains {0} words.", counter)
Call vowelcount(input, letterbyletter, vowelcounter)
Console.WriteLine("Your sentence contains {0} vowels.", vowelcounter)
End Sub
Sub wordcount(ByVal input As String, ByRef letterbyletter() As Char, ByRef
counter As Integer)
For i = 0 To Len(input) - 1
If letterbyletter(i) = " " Then
counter += 1
End If
Next
End Sub
Sub vowelcount(ByVal input As String, ByRef letterbyletter() As Char, ByRef
vowelcounter As Integer)
Dim vowels() As String = {"a", "e", "i", "o", "u"}
For i = 0 To Len(input) - 1
For j = 0 To 4
If letterbyletter(i) = vowels(j) Then
vowelcounter += 1
End If
Next
Next
End Sub
End Module

Related

iterating through each word in a richtextbox

I am trying to iterate through each word in a text document to compare each word to a list of names using the following code.
For Each word As String In TextBox1.Text.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Replace(word, vbCrLf, "")
word = Trim(TrimPunctuation(word))
MsgBox(word)
next
Private Function TrimPunctuation(ByVal value As String) As String
Dim removeFromStart As Integer = 0
For i As Integer = 0 To value.Length - 1 Step 1
If Char.IsPunctuation(value(i)) Then
removeFromStart += 1
Else
Exit For
End If
Next
Dim removeFromEnd As Integer = 0
For i As Integer = value.Length - 1 To 0 Step -1
If Char.IsPunctuation(value(i)) Then
removeFromEnd += 1
Else
Exit For
End If
Next
Return Trim(value.Substring(removeFromStart,
value.Length - removeFromEnd - removeFromStart))
End Function
For the most part it is working, but at the end of each sentence, it returns the last word including punctuation and the carriage return and the first word of the next sentence.
Dinner.
Then
I created a list to hold the output.
Next I removed any hard returns.
The line is split into words. The small c following the space character tells the compiler that this is a Char which is what the Split function is expecting.
I created a Char array of punctuation. You may want to add additional characters.
I looped through the words, trimming the punctuation. Then the punctuation free words were added to the clean list.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CleanList As New List(Of String)
Dim RemovedNewLine = RichTextBox1.Text.Replace(vbLf, " ")
Dim words = RemovedNewLine.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Dim punc() As Char = {","c, "."c, "?"c, "!"c}
For Each word In words
Dim TrimmedWord = word.Trim(punc)
CleanList.Add(TrimmedWord)
Next
For Each word In CleanList
Debug.Print(word)
Next
End Sub

How do I run two separate threads printing numbers (or words) in ascending and descending order?

I need to write a program for my online class. Here is the prompt:
Write a program to run two separate threads printing numbers (or words) in ascending and descending orders. The numbers (or words) should be given by the user.
I think I have the threads down, but I'm confused on how I would have the code take the user input and then print it in either ascending/descending order. So basically I'm confused on the syntax/methods that would need to be used.
Here is the code I have so far:
Module Module1
Sub Main()
Dim A As System.Threading.Thread = New Threading.Thread(AddressOf ThreadA)
Dim B As System.Threading.Thread = New Threading.Thread(AddressOf ThreadB)
A.Start()
End Sub
Sub ThreadA()
Dim nl As String = Environment.NewLine
Console.WriteLine("Enter a word:")
Dim x = Console.ReadLine()
End Sub
Sub ThreadB()
Dim nl As String = Environment.NewLine
Console.WriteLine("Enter a word:")
Dim x = Console.ReadLine()
End Sub
End Module
I think that you've misunderstood the question slightly. The program below takes input for 5 numbers each for two word lists, sorts each wordlist and then starts 2 threads to write each word to the console. The multi-threading is demonstrated by the way the lines from each wordlist are output to the console.
Each list is in fact in alphabetical order but multi-threading means that as both of the pieces of code run "at the same time", they don't run at exactly the same time, so the output statements don't get printed in exact alternate order. You might get a few of one word list clumped together because of the way multi-threading happens. I've added a line to sleep each thread for different amounts of time to highlight the threads running independant of each other.
Module Module1
Dim wordlist1 As New List(Of String)
Dim wordlist2 As New List(Of String)
Sub Main()
Dim A As System.Threading.Thread = New Threading.Thread(AddressOf ThreadA)
Dim B As System.Threading.Thread = New Threading.Thread(AddressOf ThreadB)
Dim word As String
For i As Integer = 1 To 5
Console.WriteLine("Enter List 1 word " & i.ToString & ":")
word = Console.ReadLine()
wordlist1.Add(word)
Next
For i As Integer = 1 To 5
Console.WriteLine("Enter List 2 word " & i.ToString & ":")
word = Console.ReadLine()
wordlist2.Add(word)
Next
Dim sortOrder As String = ""
Do
Console.WriteLine("Do you want to sort in ascending order or descending. Enter 'a' or 'd'")
sortOrder = Console.ReadLine().ToLower
Loop Until sortOrder = "a" Or sortOrder = "d"
wordlist1.Sort()
wordlist2.Sort()
If sortOrder = "d" Then
wordlist1.Reverse()
wordlist2.Reverse()
End If
A.Start()
B.Start()
Console.ReadLine()
End Sub
Sub ThreadA()
For Each word As String In wordlist1
Console.WriteLine("List 1 :" & word)
Thread.Sleep(40)
Next
End Sub
Sub ThreadB()
For Each word As String In wordlist2
Console.WriteLine("List 2 :" & word)
Thread.Sleep(80)
Next
End Sub
End Module

How to append an integer to an array in visual basic

I'm making a program that takes a sentence with no punctuation as an input, then searches for how many occurrences there are of a specific word.
Dim sntnce As String
Dim srchWord As String
Dim words As String()
Dim word As String
Dim count As Integer
Dim index As New System.Text.StringBuilder()
Console.WriteLine("Enter your sentence: ")
sntnce = Console.ReadLine()
sntnce = LCase(sntnce)
Console.WriteLine("Enter the word you want to find the position of: ")
srchWord = Console.ReadLine()
srchWord = LCase(srchWord)
words = sntnce.Split(New Char() {" "c})
Console.WriteLine(" ")
For Each word In words
If word = srchWord Then
index.Append(count)
count += 1
Else
count += 1
End If
Next
Console.WriteLine("Your word appears in the position(s)...")
Console.WriteLine(index)
Console.ReadLine()
The for loop takes the index of a word if found in a sentence and appends it to a string, but I would like to append it to an array so that the values for indexes can be outputted separately, however I can't find any solutions that help. How can I do this? Thanks
Arrays are of fixed size only. When dealing with collections that you want to add, remove or insert use List(Of T).
I think what you want is the following:
Sub Main()
Dim sntnce As String
Dim srchWord As String
Dim words As String()
Dim word As String
Dim count As Integer
Console.WriteLine("Enter your sentence: ")
sntnce = Console.ReadLine()
sntnce = LCase(sntnce)
Console.WriteLine("Enter the word you want to find the position of: ")
srchWord = Console.ReadLine()
srchWord = LCase(srchWord)
words = sntnce.Split(New Char() {" "c})
Console.WriteLine(" ")
' Create an expandable list of integers 'index_list'
Dim index_list As New List(Of Integer)
For index As Integer = 1 To words.Length
' It's recommened to use `Equals()` for string equality instead of `=`
' Arrays in VB.NET are 0-based so the i-th elements is located in `list(i-1)`
If words(index - 1).Equals(srchWord) Then
' Add index to list if there is a match
index_list.Add(index)
End If
Next
' Create a fixed array of strings to hold the character representation of the integer index array.
' Since I know the size I can use an array instead of a list.
Dim index_list_string As String() = New String(index_list.Count) {}
For index As Integer = 1 To index_list.Count
' One to one mapping of integer to string
index_list_string(index - 1) = index_list(index - 1).ToString()
Next
Console.WriteLine("Your word appears in the position(s)...")
' Take the array of strings and combine it into one string with commas in between using the `.Join()` function
' For example `{"A","B","C"} => "A, B, C"
Console.WriteLine(String.Join(", ", index_list_string))
Console.ReadLine()
End Sub

permutation not accepting large words

the vb.net code below permutates a given word...the problem i have is that it does not accept larger words like "photosynthesis", "Calendar", etc but accepts smaller words like "book", "land", etc ...what is missing...Pls help
Module Module1
Sub Main()
Dim strInputString As String = String.Empty
Dim lstPermutations As List(Of String)
'Loop until exit character is read
While strInputString <> "x"
Console.Write("Please enter a string or x to exit: ")
strInputString = Console.ReadLine()
If strInputString = "x" Then
Continue While
End If
'Create a new list and append all possible permutations to it.
lstPermutations = New List(Of String)
Append(strInputString, lstPermutations)
'Sort and display list+stats
lstPermutations.Sort()
For Each strPermutation As String In lstPermutations
Console.WriteLine("Permutation: " + strPermutation)
Next
Console.WriteLine("Total: " + lstPermutations.Count.ToString)
Console.WriteLine("")
End While
End Sub
Public Sub Append(ByVal pString As String, ByRef pList As List(Of String))
Dim strInsertValue As String
Dim strBase As String
Dim strComposed As String
'Add the base string to the list if it doesn't exist
If pList.Contains(pString) = False Then
pList.Add(pString)
End If
'Iterate through every possible set of characters
For intLoop As Integer = 1 To pString.Length - 1
'we need to slide and call an interative function.
For intInnerLoop As Integer = 0 To pString.Length - intLoop
'Get a base insert value, example (a,ab,abc)
strInsertValue = pString.Substring(intInnerLoop, intLoop)
'Remove the base insert value from the string eg (bcd,cd,d)
strBase = pString.Remove(intInnerLoop, intLoop)
'insert the value from the string into spot and check
For intCharLoop As Integer = 0 To strBase.Length - 1
strComposed = strBase.Insert(intCharLoop, strInsertValue)
If pList.Contains(strComposed) = False Then
pList.Add(strComposed)
'Call the same function to review any sub-permutations.
Append(strComposed, pList)
End If
Next
Next
Next
End Sub
End Module
Without actually creating a project to run this code, nor knowing how it 'doesn't accept' long words, my answer would be that there are a lot of permutations for long words and your program is just taking much longer than you're expecting to run. So you probably think it has crashed.
UPDATE:
The problem is the recursion, it's blowing up the stack. You'll have to rewrite your code to use an iteration instead of recursion. Generally explained here
http://www.refactoring.com/catalog/replaceRecursionWithIteration.html
Psuedo code here uses iteration instead of recursion
Generate list of all possible permutations of a string

Using Functions in Visual Basic

The program I'm working on has two different functions, one that calculates the number of syllables in a text file, and another that calculates the readability of the text file based on the formula
206.835-85.6*(Number of Syllables/Number of Words)-1.015*(Number of Words/Number of Sentences)
Here are the problems I'm having:
I'm supposed to display the contents of the text file in a multi-line text box.
I'm supposed to display the answer I get from the function indexCalculation in a label below the text box.
I'm having trouble calling the function to actually have the program calculate the answer to be displayed in the label.
Here is the code I have so far.
Option Strict On
Imports System.IO
Public Class Form1
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim open As New OpenFileDialog
open.Filter = "text files |project7.txt|All file |*.*"
open.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
If open.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim selectedFileName As String = System.IO.Path.GetFileName(open.FileName)
If selectedFileName.ToLower = "project7.txt" Then
Dim text As String = File.ReadAllText("Project7.txt")
Dim words = text.Split(" "c)
Dim wordCount As Integer = words.Length
Dim separators As Char() = {"."c, "!"c, "?"c, ":"c}
Dim sentences = text.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Dim sentenceCount As Integer = sentences.Length
Dim vowelCount As Integer = 0
For Each word As String In words
vowelCount += CountSyllables(word)
Next
vowelCount = CountSyllables(text)
Label1.Show(indexCalculation(wordCount, sentenceCount, vowelCount))
Else
MessageBox.Show("You cannot use that file!")
End If
End If
End Sub
Function CountSyllables(word As String) As Integer
word = word.ToLower()
Dim dipthongs = {"oo", "ou", "ie", "oi", "ea", "ee", _
"eu", "ai", "ua", "ue", "au", "io"}
For Each dipthong In dipthongs
word = word.Replace(dipthong, dipthong(0))
Next
Dim vowels = "aeiou"
Dim vowelCount = 0
For Each c In word
If vowels.IndexOf(c) >= 0 Then vowelCount += 1
Next
If vowelCount = 0 Then
vowelCount = 1
End If
Return vowelCount
End Function
Function indexCalculation(ByRef wordCount As Integer, ByRef sentenceCount As Integer, ByRef vowelCount As Integer) As Integer
Dim answer As Integer = CInt(206.835 - 85.6 * (vowelCount / wordCount) - 1.015 * (wordCount / sentenceCount))
Return answer
End Function
End Class
Any suggestions would be greatly appreciated.
Here are my suggestions:
update your indexCalculation function to take in Integers, not strings. that way you don't have to convert them to numbers.
remove all of your extra variables you are not using. this will clean things up a bit.
remove your streamreader. it appears you are reading the text via File.ReadAllText
Label1.Show(answer) should be changed to Label1.Show(indexCalculation(wordCount,sentenceCount,vowelCount)) -- unless Label1 is something other than a regular label, use Label1.Text = indexCalculation(wordCount,sentenceCount,vowelCount))
Then for the vowelCount, you need to do the following:
Dim vowelCount as Integer = 0
For Each word as String in words
vowelCount += CountSyllables(word)
Next
Also, add the logic to the CountSyllables function to make it 1 if 0. If you don't want to include the last character in your vowel counting, then use a for loop instead of a for each loop and stop 1 character short.