How can i allow only positive number in my code - vb.net

I'm still new in VB and I have emailed my lecturer but it seems like he is quite busy and didn't have time to reply to me. Can anyone teach me with it?
Dim split = InputTextBox.Text.Split(vbNewLine)
Dim check As Boolean
For i = 0 To split.Length - 1
check = IsNumeric(split(i))
If Not check Then
Exit For
End If
Next
If check Then
FootForm.Show()
Else
MessageBox.Show("Please enter in positive number only")
End If

I am not sure how your value is stored in the form control. The below should help
Dim split as String = InputTextBox.Text.Split(vbNewLine)
Dim parsedint as Integer
If Int32.TryParse(split, parsedint) AndAlso parsedint < 0 Then
MessageBox.Show("Please enter in positive number only")
Else
FootForm.Show()
End If

You can throw a bit of LINQ at the problem:
If InputTextBox.Lines.All(Function(s)
Dim n As Double
Return Double.TryParse(s, n) AndAlso n >= 0.0
End Function) Then
'All lines represent non-negative numbers.
End If
The longhand version would be:
Dim result = True
For Each s In InputTextBox.Lines
Dim n As Double
If Not Double.TryParse(s, n) OrElse n < 0.0 Then
result = False
Exit For
End If
Next
If result Then
'All lines represent non-negative numbers.
End If

Related

How can I solve my "sub main was not found" problem?

Module PrimePairs
Public Function IsPrime(n As Long) As Boolean
Console.WriteLine("Please enter the value: ")
n = Console.ReadLine()
n = Math.Abs(n) ' Allows to consider negative prime numbers
If n < 2 Then ' Disallows -1, 0, 1
Return False
End If
Dim i As Long
i = 2
While i < n ' Note that for n = 2 we don't enter the loop and thus return True.
If n Mod i = 0 Then
Return False
End If
i += 1
End While
Return True
End Function
Public Function PrimePairs(ByVal n As Long, ByVal n2 As Long) As Integer
Dim count As Integer = 0
Console.ReadLine()
If n Mod 2 = 0 Then
For i = 1 To (n / 2) + 1
n2 = n - i
If IsPrime(i) And IsPrime(n2) = True Then
count += 1
End If
Next
Else
n2 = n - 2
If IsPrime(n2) = True Then
count = +1
End If
End If
Console.WriteLine("The result is:", count)
Return n
End Function
End Module
I want my code to calculate how many prime number twins can write the input I gave.
The problem is that your project actually does not contain a Sub Main(), as the error states.
You defined two functions in the Module Program, but console applications need a predefined entry point, which usually is the Main method.
The compiler is telling you that your project is not valid because it didn't find any entry point.
Just add a Sub Main() to get your project working, then call your functions from that method.
Example:
Option Strict On
Module Program
Sub Main(args As String())
Console.WriteLine("Please enter the value: ")
Dim input As String = Console.ReadLine()
Dim number As Long
If Long.TryParse(input, number) Then // More about this function in the answer below
Dim prime As Boolean = IsPrime(number)
If prime Then
Console.WriteLine(number & " is prime.")
Else
Console.WriteLine(number & " is not prime.")
End If
End If
Console.ReadLine()
End Sub
Function IsPrime(n As Long) As Boolean
n = Math.Abs(n) ' Allows to consider negative prime numbers
If n < 2 Then ' Disallows -1, 0, 1
Return False
End If
Dim i As Long = 2
i = 2
While i < n ' Note that for n = 2 we don't enter the loop and thus return True.
If n Mod i = 0 Then
Return False
End If
i += 1
End While
Return True
End Function
End Module
Also, I suggest you to enable Option Strict On as I added at the beginning of file. This prevents the compiler from doing implicit casts and forces you to explicitly declare your variables.
E.g., your line of code
n = Console.ReadLine()
is not valid with Option Strict On, because n is supposed to be a long, but Console.ReadLine() returns a string.
If you are a beginner, this will allow you to better understand how programming works and will help you to avoid errors - take good habits from the beginning, you can thank me later ;)
That's why I changed your code withLong.TryParse(input, number): this function returns true if provided input can be cast (=converted) to a long, and assigns the casted value to number variable.
There's a lot more I'd like to suggest you, but I would go off-topic.

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")

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)

How do you check if an input is a negative number in VB

I am trying to do some validation which checks if the value in a textbox is an integer then checks if the the value is negative. It correctly checks if the value is an integer but I can't get it to check if the value is negative.
Note: The value being entered is the number of competitions attended so comps = competition etc...
Dim comps As Integer
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
value = txtCompsEntered.Text
If value < 0 Then
lblcompsatten.ForeColor = Color.Red
txtCompsEntered.ForeColor = Color.Red
lblcompsatten.Text = "No negative numbers"
Else
lblcompsatten.ForeColor = Color.Black
txtCompsEntered.ForeColor = Color.Black
lblcompsatten.Text = ""
End If
lblcompsatten.ForeColor = Color.Black
txtCompsEntered.ForeColor = Color.Black
lblcompsatten.Text = ""
Else
lblcompsatten.ForeColor = Color.Red
txtCompsEntered.ForeColor = Color.Red
lblcompsatten.Text = "Not a number"
End If
I have already looked at this thread but it didn't seem to work
how-to-check-for-negative-values-in-text-box-in-vb
Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables. Here's an example of how it works:
Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"
'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
If comps < 0 Then
'do something
End If
Else
'I'm not an integer!
End If
'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
If comps < 0 Then
'do something
End If
End If
There are a couple of things off with your code but the main issue is using Integer.TryParse incorrectly.
Incorrect:
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
value = txtCompsEntered.Text
If value < 0 Then
Correct:
Dim value As Integer
If Integer.TryParse(txtCompsEntered.Text, value) Then
If value < 0 Then
The things to note are that Integer.TryParse will return a boolean value (true if the value can be convertan integer, false if not). It will them dump the converted value into the second parameter you pass into it. In your case, you had 'integer', which is incorrect. You should be passing in a variable and then using that variable for your comparison.
Also, be careful with your types. You have 'value' as a double when you seem to be working with integers.
Maybe try this?
If myinteger.toString.Contains("-") Then
'it's negative
Else
'it isn't
End If
Or even simplier
If myinteger < 0 Then
'it's not negative
Else
'it is negative
End if

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)