Assignment Guidance - vb.net

This is the third week of my intro to programming class and I'm stuck. I can get it to run I just can't enter more than 1 number. This is a vb console app.
Module Module1
Sub Main()
Dim highestNumber As Integer = -1000000000
Dim lowestNumber As Integer = 100000000
Dim userInput As Integer
Console.WriteLine("Input your numbers and when you are done enter -99.")
Console.WriteLine("The app will then give the highest and lowest numbers entered.")
userInput = Console.ReadLine()
While userInput <> "-99"
If userInput >= highestNumber Then
highestNumber = userInput
ElseIf userInput <= lowestNumber Then
lowestNumber = userInput
End If
End While
Console.WriteLine("The highest number you entered is: " & highestNumber)
Console.WriteLine("The lowest number you entered is: " & lowestNumber)
Console.ReadLine()
End Sub
End Module

You're only executing ReadLine once, before the loop starts, so you only get to enter one number. As it currently stands, if you don't enter -99 then you have an infinite loop since you cannot change userInput inside the loop.
You need to put a copy of userInput = Console.ReadLine() at the end of the While loop so that a new value can be entered and the logic will be re-executed.
Also, you might as well remove the = signs from your tests. No point changing the highest/lowest unless the new number is actual higher/lower.

Move this line inside your while loop
userInput = Console.ReadLine()

Here's my solution. It checks the input of the user, if it's not an integer they can try again or enter -99 and get out... You can also change how many numbers a user enters by changing a few places where it shows 2, or declare a variable and set it and then use it...
Public Sub Main()
Dim userInput As Integer = 0
Dim lstInteger As New List(Of Integer)
Console.WriteLine("Input your numbers and when you are done enter -99." & Environment.NewLine & "The app will then give the highest and lowest numbers entered.")
Do Until userInput = -99
If Integer.TryParse(Console.ReadLine(),userInput) AndAlso userInput <> -99 Then
lstInteger.Add(userInput)
If lstInteger.Count = 2 Then Exit Do
userInput = 0
If Integer.TryParse(Console.ReadLine(), userInput) AndAlso userInput <> -99 Then
lstInteger.Add(userInput)
If lstInteger.Count = 2 Then Exit Do
Else
If userInput = -99 Then Exit Do Else Console.WriteLine("Please enter a number.")
End If
Else
If userInput <> - 99 AndAlso userInput = 0 Then
Console.WriteLine("Please enter a number.")
Else
Exit Do
End If
End If
Loop
If lstInteger.Count = 2 Then
Console.WriteLine("The highest number you entered is: " & lstInteger.Max.ToString)
Console.WriteLine("The lowest number you entered is: " & lstInteger.Min.ToString)
End If
Console.ReadLine()
End Sub

Related

I want to save a file in VB.net from the amount of tries a user has

I'm a student trying to learn Console App .Net Framework and I want to code a random number between 0000 and 9999 (as a pin that you need to guess). Thus far I've had to set it as a random number from 1000 to 9999 as the system wont let me do 0000. Furthermore, I want to save the amount of tries the user has as a text file e.g. if the user tries 50 times, I'd like it to say
Username Tries
I've tried Randomise() Rnd(*9999) and X = EasyNum.Next(1000, 9999) but then I can't compare unless I convert that to an integer.
Module Module1
Dim Tries As String = 0
Dim EasyNum As New Random
Dim HardNum As New Random
Dim Attempt As String
Sub Main()
Dim Difficulty As String
Console.WriteLine("Welcome to MasterMind")
Console.WriteLine("Choose between Easy and Hard difficulty")
Difficulty = Strings.LCase(Console.ReadLine)
While Difficulty <> "easy" And Difficulty <> "hard"
Console.WriteLine("That's not a correct mode")
Difficulty = Strings.LCase(Console.ReadLine)
End While
If Difficulty = "easy" Then
Easy()
ElseIf Difficulty = "hard" Then
Hard()
End If
End Sub
Dim EasyGuess1 As Integer
Dim EasyGuess2 As Integer
Dim X As String
Dim Y As Integer
Sub Easy()
Console.WriteLine("You have chosen the easy difficulty")
Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
Console.WriteLine("Enter your guess")
X = EasyNum.Next(1000, 9999)
Console.WriteLine(X)
EasyGuess1 = Console.ReadLine
Tries = +1
If Mid(CStr(EasyGuess1), 1, 1) = Mid(CStr(X), 1, 1) Then
Console.WriteLine("You have 1 number correct, try again?")
Attempt = Strings.LCase(Console.ReadLine)
While Attempt <> "yes" And Attempt <> "no"
Console.WriteLine("Enter either yes or no")
Attempt = Strings.LCase(Console.ReadLine)
End While
ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
Console.WriteLine("You have 1 number correct, try again?")
Attempt = Strings.LCase(Console.ReadLine)
While Attempt <> "yes" And Attempt <> "no"
Console.WriteLine("Enter either yes or no")
Attempt = Strings.LCase(Console.ReadLine)
End While
End If
If Attempt = "yes" Then
EasyYes()
ElseIf Attempt = "no" Then
EasyNo()
End If
Console.WriteLine("incorrect")
Console.ReadKey()
End Sub
Sub EasyYes()
Console.WriteLine("Enter a new guess")
EasyGuess1 = Console.ReadLine
End Sub
Sub EasyNo()
Dim Save As String
Dim File As System.IO.File
Console.WriteLine("Do you want to save your tries? Enter Yes or no")
Save = Strings.LCase(Console.ReadLine)
If Save = "yes" Then
System.IO.File.Create(Tries, "C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test")
End If
End Sub
Sub Hard()
Console.WriteLine("You have chosen the hard difficulty")
End Sub
Sub HardYes()
End Sub
Sub HardNo()
End Sub
End Module
When I try to save the tries, I get this:
System.InvalidCastException: 'Conversion from string "C:\X\Code\VB\Challenges\Cha" to type 'Integer' is not valid.'
InnerException
FormatException: Input string was not in a correct format.
Which I don't understand myself.
Comments in line. Please read all comments. This program is still not working too well but I will leave it to you to tidy up.
Module Module1
Dim Tries As Integer = 0
'Use only a single instance of Random
Dim EasyNum As New Random
'Dim HardNum As New Random
Dim Attempt As String
Sub Main()
Dim Difficulty As String
Console.WriteLine("Welcome to MasterMind")
Console.WriteLine("Choose between Easy and Hard difficulty")
Difficulty = Strings.LCase(Console.ReadLine)
'AndAlso prevents the second condition from executing if the first condition is true
While Difficulty <> "easy" AndAlso Difficulty <> "hard"
Console.WriteLine("That's not a correct mode")
Difficulty = Strings.LCase(Console.ReadLine)
End While
If Difficulty = "easy" Then
Easy()
'ElseIf Difficulty = "hard" Then
' Hard() 'Not implemented
End If
End Sub
'Dim EasyGuess2 As Integer
'Dim X As String
'Dim Y As Integer
Sub Easy()
Dim EasyGuess1 As Integer
Console.WriteLine("You have chosen the easy difficulty")
Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
Console.WriteLine("Enter your guess")
'X = EasyNum.Next(1000, 9999)
'The next method returns a non-negative integer not a string
'To get 0 to 9999 with leading zeros do the following
'Returns a non-negative random integer that is less than the specified maximum.
Dim X = EasyNum.Next(10000).ToString("0000")
Console.WriteLine(X)
'Console.ReadLine returns a String. You should Not assign a String to an Integer
'EasyGuess1 = Console.ReadLine
'Never trust a user :-) Use .TryParse to set the variable
Integer.TryParse(Console.ReadLine, EasyGuess1)
'This just assigns the value of 1 to Tries
'Tries = +1
'If you want to increment Tries
Tries += 1
'Let's compare apples and apples
'If you just convert EasyGuess1 To a string and EasyGuess1 is 54
'the string is "54" You want a 4 character string
'If Mid(EasyGuess1.ToString("0000"), 1, 1) = Mid(CStr(X), 1, 1) Then
' 'but you only compared the first character, what about the rest?
' 'Mid is aroung for backward compatibility. It should not be used for new code.
' 'The position Integer is one based which is not at all sympatico with .net
' Console.WriteLine("You have 1 number correct, try again?")
' Attempt = Strings.LCase(Console.ReadLine)
' While Attempt <> "yes" And Attempt <> "no"
' Console.WriteLine("Enter either yes or no")
' Attempt = Strings.LCase(Console.ReadLine)
' End While
'ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
' Console.WriteLine("You have 1 number correct, try again?")
' Attempt = Strings.LCase(Console.ReadLine)
' While Attempt <> "yes" And Attempt <> "no"
' Console.WriteLine("Enter either yes or no")
' Attempt = Strings.LCase(Console.ReadLine)
' End While
'End If
Dim CorrectCharacters = TestInput(EasyGuess1, X)
Console.WriteLine($"You have guessed {CorrectCharacters} correctly. Try again?")
'Use the .net way. The framework is available to all languages in .net
'so it will be easier to learn other languages.
Attempt = (Console.ReadLine).ToLower
If Attempt = "yes" Then
EasyYes()
ElseIf Attempt = "no" Then
EasyNo()
End If
Console.WriteLine("incorrect")
Console.ReadKey()
End Sub
Sub EasyYes()
Dim guess As Integer
Console.WriteLine("Enter a new guess")
'You are doing this twice ???
'EasyGuess1 = Console.ReadLine
Integer.TryParse(Console.ReadLine, guess)
'EasyGuess1 will be 0 if the entry is other than an integer
'Very nice bu this Sub doesn't do anything
End Sub
Sub EasyNo()
Dim Save As String
'Unused local variable and if you needed this it is a poor choice for a variable name
'Dim File As System.IO.File
Console.WriteLine("Do you want to save your tries? Enter Yes or no")
Save = Console.ReadLine.ToLower
If Save = "yes" Then
'Give the file name an extension.
'When you pass (String, Integer) to the Create method, the Integer is the number of bytes
'buffered for reads And writes to the file.
'Not exactly what you were expecting.
'System.IO.File.Create("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries)
'Imports System.IO at top of file
File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries.ToString)
End If
End Sub
Sub Hard()
Console.WriteLine("You have chosen the hard difficulty")
End Sub
Private Function TestInput(Guessed As Integer, RandString As String) As Integer
Dim Correct As Integer
Dim Guess As String = Guessed.ToString("0000")
'A String can be a Char array
'Here we check each character in the 2 strings for equality
'and if true then increment Correct
For i = 0 To 3
If Guess(i) = RandString(i) Then
Correct += 1
End If
Next
Return Correct
End Function
End Module
There are a lot of issues, but I don't want to spoil it for you.
I definitely recommend to put "Option Strict On" in the project settings, so you immediately see where there are conversion errors (a string assigned to a integer etc).
To save the file, it should be something like
If Save = "yes" Then
File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test", Tries.ToString())
End If
(there are also File.Append... functions).
The Random class is a bit tricky, this is an object that provides random values and is not yet the random value itself. Always use the same random object for all different numbers, otherwise you might get the same number:
Private Randomizer As New Random(Environment.TickCount)
Private EasyNum As Int32 = Randomizer.Next(0, 10000) '0 to 9999
Private HardNum As Int32 = Randomizer.Next(0, 100000) '0 to 99999
The "from" value of the randomizer's Next method is always inclusive, the "to" value exclusive, for whatever reasons.
To increment a variable, the syntax is
Tries += 1
instead of "Tries = +1"
To write a number with leading digits, use might use
Console.Out.WriteLine($"The correct solution would have been: {EasyNum:0000}")
or
EasyNum.ToString("0000")

vb.net readline or readkey don't want to stop my program

my code is working i tried it separately but the problem here is that when i'm putting them together , the readkey or readline don't stop the program and the do loop is not working too, can someone take a look please thank in advance
Dim count As Integer
Dim first(5) As Integer
Dim temp As Integer
Dim answer As String
Sub Main()
Do
Console.WriteLine("Please enter your first number")
first(0) = Console.ReadLine
Console.WriteLine("Please enter your second number")
first(1) = Console.ReadLine
Console.WriteLine("Please enter your third number")
first(2) = Console.ReadLine
Console.WriteLine("Please enter your fourth number")
first(3) = Console.ReadLine
Console.WriteLine("Please enter your fifth number")
first(4) = Console.ReadLine
Console.WriteLine("Please enter your sixth number")
first(5) = Console.ReadLine
randomnumber()
Console.WriteLine("do you want to continue?")
answer = Console.ReadLine
Loop Until (answer = "n" Or answer = "No")
Console.ReadKey()
End Sub
Sub randomnumber()
Dim r As New List(Of Integer)
Dim rg As New Random
Dim rn As Integer
Dim arraywinner(5) As Integer
Do
rn = rg.Next(1, 40)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
'store bane random value in array'
arraywinner(0) = r(0)
arraywinner(1) = r(1)
arraywinner(2) = r(2)
arraywinner(3) = r(3)
arraywinner(4) = r(4)
arraywinner(5) = r(5)
'print random numbers
count = 0
While count <= 5
Console.WriteLine("the randoms numbers are : " & arraywinner(count))
count = count + 1
End While
'look for the amount of number
temp = 0
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If arraywinner(count1) = first(count2) Then
temp = temp + 1
End If
Next
Next
If temp = 1 Or temp = 0 Then
Console.WriteLine("You have got " & temp & " number")
Else
Console.WriteLine("You have got " & temp & " numbers")
End If
money(temp)
End Sub
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
You have two problems in money():
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
Your parameter is t1, but you're using temp in all of your code. As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all.
Secondly, you have End in the block for 0, 1, or 2 matches. The End statement Terminates execution immediately., which means the program just stops. Get rid of that line.
There are so many other things you could change, but that should fix your immediate problem...
I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place.
Module Module1
Private rg As New Random
Public Sub Main()
'keep variables with as narrow a scope as possible
Dim answer As String = Nothing
'This line initializes and array of strings called words
Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"}
Dim WinnersChosen(5) As Integer
Do
'To shorten your code use a For loop
For index = 0 To 5
Console.WriteLine($"Please enter your {words(index)} number")
WinnersChosen(index) = CInt(Console.ReadLine)
Next
Dim RandomWinners = GetRandomWinners()
Console.WriteLine("The random winners are:")
For Each i As Integer In RandomWinners
Console.WriteLine(i)
Next
Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen)
If WinnersCount = 1 Then
Console.WriteLine($"You have guessed {WinnersCount} number")
Else
Console.WriteLine($"You have guessed {WinnersCount} numbers")
End If
Dim Winnings = Money(WinnersCount)
'The formatting :N0 will add the commas to the number
Console.WriteLine($"Your winnings are {Winnings:N0}")
Console.WriteLine("do you want to continue? y/n")
answer = Console.ReadLine.ToLower
Loop Until answer = "n"
Console.ReadKey()
End Sub
'Too much happening in the Sub
'Try to have a Sub or Function do only one job
'Name the Sub accordingly
Private Function GetRandomWinners() As List(Of Integer)
Dim RandomWinners As New List(Of Integer)
Dim rn As Integer
'Good use of .Contains and good logic in Loop Until
Do
rn = rg.Next(1, 40)
If Not RandomWinners.Contains(rn) Then
RandomWinners.Add(rn)
End If
Loop Until RandomWinners.Count = 6
Return RandomWinners
End Function
Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer
Dim temp As Integer
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If r(count1) = WinnersChosen(count2) Then
temp = temp + 1
End If
Next
Next
Return temp
End Function
Private Function Money(Count As Integer) As Integer
'A Select Case reads a little cleaner
Select Case Count
Case 3
Return 120
Case 4
Return 500
Case 5
Return 10000
Case 6
Return 1000000
Case Else
Return 0
End Select
End Function
End Module

How to don't allow the user to enter an amount of more than 100

I have this case where I need that the user enters some data. All I need is to allow the user to enter numbers from 0 to 100, if the user is entering an amount bigger than 100, than display a message like: please enter number from 0 to 100 and then show them again where they need to enter that number.
For example, Console.Write("Español: ") in the terminal is:
Español: ' the user should enter the number here
if the user enters more than 100, then display this:
Please enter number from 0 to 100. Español: ' here enter the number again
I was thinking on doing this as in the code below, with an If ... Else, but, is there a better way?
Here is the actual code:
Sub Main()
Dim Español1 As Integer
Dim Matematicas1 As Integer
Dim Ciencias1 As Integer
Dim EstudiosSociales1 As Integer
Dim Ingles1 As Integer
Dim ArtesPlasticas1 As Integer
Dim ArtesIndustriales1 As Integer
Select Case Menu
Case 2
Console.Write("Ingrese las notas: ")
Console.ReadLine()
Console.Write("Español: ")
' I was thinking on doing this
If Console.ReadLine() >= 100 Then
Console.Write("La nota debe ser 100 o menos: ")
Español1 = Console.ReadLine()
Else
Español1 = Console.ReadLine()
End If
If Español1 = True Then
Console.Write("Matematicas: ")
Matematicas1 = Console.ReadLine()
End If
Console.Write("Ciencias: ")
Ciencias1 = Console.ReadLine()
Console.Write("Estudios Sociales: ")
EstudiosSociales1 = Console.ReadLine()
Console.Write("Ingles: ")
Ingles1 = Console.ReadLine()
Console.Write("Artes plasticas: ")
ArtesPlasticas1 = Console.ReadLine()
Console.Write("Artes Industriales: ")
ArtesIndustriales1 = Console.ReadLine()
Console.Clear()
End Select
End Sub
So, any suggestions?
I'm not really experienced with VB, but try this:
Dim n as Integer
n = Console.WriteLine()
Do While n >= 100
Console.WiteLine("Enter new Value:") 'Sorry, no pienso la lengua español :(
n = Console.ReadLine()
Loop
Edit 3.0
Add your subject names into the array subjects.
Sub Main()
Dim subjects As Array = {"Math", "English", "German"} 'Three example names
Dim subjectsInt As New Dictionary(Of String, Integer)
Dim i, input As Integer
Dim check, FirstTry As Boolean
For i = 0 To (subjects.Length - 1)
check = False
FirstTry = True
Do
If FirstTry = True Then
Console.WriteLine(subjects(i) & ": ")
FirstTry = False
Else
Console.WriteLine("Please enter a value between 1 and 100" & " (" & subjects(i) & "):")
End If
input = Console.ReadLine()
If input <= 100 And input > 0 Then
subjectsInt.Add(subjects(i), input)
check = True
End If
Loop While check = False
Next
For i = 0 To (subjects.Length - 1)
Console.WriteLine(subjects(i) & ": " & subjectsInt(subjects(i)))
Next
Console.ReadLine()
End Sub
Well I dont know VBA unfortunately . But I believe in every language is the same. You do a do {}while cycle and in the while you check if you conditions are met. And until they are met you continue reading from the console. Good look with your VBA :)

Hangman VB Not Working

I am making a hangman game on VB. An help is appreciated
All I have is that player 1 enters a word. The program then puts it into an array, which sorts it into letters. The player 2 (on the same computer) tries to guess the word, one letter at the time. They type in a letter and the program will go trough the array to check if there are any letter in the word. If there are it will show the letter (leaving the others blank) and leave the scoring system at 10 (I still need to put this in) If they guess wrong the letters will remain covered and it will minus 1 of the scoring system.
Module Module1
Sub Main()
Dim myword, guess As String
Dim mywordlen As Integer
Dim flag As Boolean
Console.WriteLine("Player 1, please enter a word to guess")
myword = Console.ReadLine()
mywordlen = myword.Length
Dim answer(mywordlen) As Char
For x = 0 To mywordlen - 1
answer(x) = "_"
While answer > 0 Then
Console.WriteLine("Please guess a letter")
guess = Console.ReadLine()
flag = False
For x = 0 To mywordlen - 1
If guess = myword Then {0}
answer(x) = guess
flag = True
Console.WriteLine("The answer is, {0}")
Next
Next
End Sub
Dim myword, guess As String
Dim mywordlen, x As Integer
Dim flag As Boolean
Console.WriteLine("Player 1, please enter a word to guess")
myword = Console.ReadLine()
mywordlen = myword.Length - 1
Dim answer(mywordlen), displayword(mywordlen) As Char
Dim score As Integer = 10
For x = 0 To mywordlen
answer(x) = Mid(myword, x + 1, 1)
displayword(x) = "_"
Next
While score > 0
Console.WriteLine("Please guess a letter")
guess = Console.ReadLine() 'Assumes user only types one letter
flag = False
For x = 0 To mywordlen
If guess = answer(x) Then
displayword(x) = guess
flag = True
End If
Next
If flag Then
If New String(displayword) = myword Then
Console.WriteLine("Congratulations! You won!")
Exit While
Else
Console.WriteLine("Correct! {0}", New String(displayword))
End If
Else
Console.WriteLine("Incorrect. {0}", New String(displayword))
score -= 1
End If
End While
Console.WriteLine("Game over. The word was {0}", myword)

Most Efficient Way To Write This Loop VB.Net

Good afternoon all, I am beginning my first forays into programming and have decided to begin with VB.net as I can get VS2010 professional free through MS Dreamspark program.
I have been following some basic tutorials online and am now writing a small program that runs a loop to add all the numbers together between two numbers input by the user.
Below is the code I have written:
Public Class Form1
Private Sub cmdAddNumbers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddNumbers.Click
Dim NumberOne As Integer
Dim NumberTwo As Integer
Dim Result As Integer
Dim i As Integer
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text > NumberOne And IsNumeric(txtNumberTwo.Text) Then
NumberTwo = txtNumberTwo.Text
End If
For i = NumberOne To NumberTwo
Result = Result + i
Next i
txtResult.Text = Result
txtNumberOne.Clear()
txtNumberTwo.Clear()
End Sub
End Class
Now, I am wondering if I have written the most efficent If statements to execute this code or if they can be written any simpler with AND/OR statements to possibly remove some of the ElseIf's.
Any insight is greatly appreciated.
Thank you,
Alex
You should start with putting Option Strict On at the top of your code to force yourself to write code without implicit conversions between strings and numbers. An example of a pitfall in your code is where you compare the string value txtNumberTwo.Text to the numeric value NumberOne; it isn't obvious if the string is converted to a number so that the comparison works properly, or if the number is converted to a string so that it does a string comparison instead.
You can use the Int32.TryParse method to parse each number only once instead of three times:
Dim numberOne As Integer
Dim numberTwo As Integer
Dim result As Integer
If Not Int32.TryParse(txtNumberOne.Text, numberOne) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf numberOne <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
If Not Int32.TryParse(txtNumberTwo.Text, numberTwo) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf numberTwo < numberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
End If
Your loop is not needed at all. You can calculate the sum directly:
Result = (numberOne + numberTwo) * (numberTwo + 1 - numberOne) / 2
What about:
If Not IsNumeric(txtNumberOne.Text) Or txtNumberOne.Text <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
Else
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Or txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
Else
NumberTwo = txtNumberTwo.Text
End If
Be aware that if NumberOne is equal to Textbox2.Text, NumberTwo is never assigned
i think the best solution for you is just set the textboxes to be able to accept only numbers, that way you can avoid all the checks if the texts is numeric or not and only check if its bigger than zero.
to set the textboxes to accept only numbers copy this function:
Private Function TrapKey(ByVal KCode As String) As Boolean
If (KCode >= 48 And KCode <= 57) Or KCode = 8 Then
TrapKey = False
Else
TrapKey = True
End If
End Function
and in the keypress event of the textboxes add
e.Handled = TrapKey(Asc(e.KeyChar))
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
The third If is superflious. We know it must be IsNumeric, as it passed the first If, and we know it cannot be 0, as it passed the second If. (You also make no allowances at all, if it happens to be negative)
Now, it been a while since I last did VB.Net, but I'm pretty sure it still have a distinct between strings & integers, which means txtNumberOne.Text = 0 shouldn't even compile.
And also, why are you making your users guess what a "valid number" is?
Dim numberOne as Integer
If IsNumeric(txtNumberOne.Text) Then
numberOne = CInt(txtNumberOne.Text)
else
numberOne = -1;
End If
If numberOne < 1
MsgBox("Please Enter A Positive Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
Dim doub As Double
If Not (Double.TryParse(txtNumberOne.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Else
NumberOne = doub
End If
If Not (Double.TryParse(txtNumberTwo.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Else
NumberTwo = doub
End If
I think this is waht you are looking for
Result = (NumberTwo * (NumberTwo + 1) / 2) - ((NumberOne - 1) * (NumberOne) / 2)