Binary value can't show properly - vb.net

I have a problem converting the integer number to binary number, anyone can guide me on which one I get the error in my coding? Thanks.
Imports System.Text
Module Module1
Sub Main()
Dim number As Integer
Console.Write("Please Enter Number: ")
number = Console.ReadLine()
'Print the results
Console.WriteLine("The binary is: " & ConvertDecimalToBinary(number))
End Sub
Private Function ConvertDecimalToBinary(number As Integer) As String
Dim remainder As Integer
Dim num As Integer
'Create a string for binary
Dim sb = New StringBuilder()
Do
remainder = number Mod 2
sb.Insert(0, remainder)
num \= 2
Loop While num = 1
Return remainder
End Function
End Module
This is my output when I insert number 5 then give me the binary number is 1:
I want the output like below the sample picture:

EDIT : There is a more simple solution, here you go :
Sub Main()
Dim number As Integer
Console.Write("Please enter a number : ")
number = Convert.ToInt32(Console.ReadLine)
'Print the results
Console.WriteLine("The binary result of the number is : " & Convert.ToString(number, 2))
Console.ReadKey()
End Sub
This is the translated code from C# to VB from this post :
Private Function ConvertDecimalToBinary(number As Integer) As String
Dim bits As Char() = New Char(32) {}
Dim i As Integer
While number <> 0
bits(i) = If((number And 1) = 1, "1"c, "0"c)
i += 1
number >>= 1
End While
Array.Reverse(bits, 0, i)
Return New String(bits)
End Function
So your main function would be something like this :
Sub Main()
Dim number As Integer
Console.Write("Please enter a number : ")
number = Convert.ToInt32(Console.ReadLine)
'Print the results
Console.WriteLine("The binary result of the number is : " & ConvertDecimalToBinary(number))
Console.ReadKey()
End Sub

There is an easier way, you can try it.https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?redirectedfrom=MSDN&view=netframework-4.8
Sub Main()
Dim number As Integer
Console.Write("Please Enter Number: ")
number = Console.ReadLine()
'Print the results
Console.WriteLine("The binary is: " & Convert.ToString(number, 2))
Console.ReadKey()
End Sub

Related

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

Word and vowel count in VB 2017

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

How to indentify the positions that a word occurs in a given text?

I am developing a program where you can input a sentence and then search for a word. The program will then tell you at which positions this word occurs. I have written some code but do not know how to continue.
Module Module1
Sub Main()
Dim Sentence As String
Dim SentenceLength As Integer
Dim L As Integer = 0
Dim LotsofText As String = Console.ReadLine
Console.WriteLine("Enter your word ") : Sentence = Console.ReadLine
For L = 1 To LotsofText.Length
If (Mid(LotsofText, L, 1)) = " " Then
End If
L = L + 1
Dim TextCounter As Integer = 0
Dim MainWord As String = Sentence
Dim CountChar As String = " "
Do While InStr(MainWord, CountChar) > 0
MainWord = Mid(MainWord, 1 + InStr(MainWord, CountChar), Len(MainWord))
TextCounter = TextCounter + 1
'Text = TextCounter + 2
' Console.WriteLine(Text)
Loop
Console.WriteLine(TextCounter)
Console.Write("Press Enter to Exit")
Console.ReadLine()
End Sub
End Module
Transform this piece of code from C# to Visual Basic. match.Index will indicate the position of the given word.
var rx = new Regex("your");
foreach (Match match in rx.Matches("This is your text! This is your text!"))
{
int i = match.Index;
}
To find only words and not sub-strings (for example to ignore "cat" in "catty"):
Dim LotsofText = "catty cat"
Dim Sentence = "cat"
Dim pattern = "\b" & Regex.Escape(Sentence) & "\b"
Dim matches = Regex.Matches(LotsofText, pattern)
For Each m As Match In matches
Debug.Print(m.Index & "") ' 6
Next
If you want to find sub-strings too, you can remove the "\b" parts.
If you add this function to your code:
Public Function GetIndexes(ByVal SearchWithinThis As String, ByVal SearchForThis As String) As List(Of Integer)
Dim Result As New List(Of Integer)
Dim i As Integer = SearchWithinThis.IndexOf(SearchForThis)
While (i <> -1)
Result.Add(i)
i = SearchWithinThis.IndexOf(SearchForThis, i + 1)
End While
Return Result
End Function
And call the function in your code:
Dim Indexes as list(of Integer) = GetIndexes(LotsofText, Sentence)
Now GetIndexes will find all indexes of the word you are searching for within the sentence and put them in the list Indexes.

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

Generate unique serial number incrementally

I am writing a vb.net program to generate a three digit serial number I will use in printing a barcode.
The requirements are the counter must count:
001 - 999, A00 - A99, B00 - B99, ..., Z00 - Z99
I cannot use the letters O and I
This code simply increments the value I pass to it by 1. I first check if the value is <=998 and if so return the value in 3 digits. I had to put this in a Try statement because passing the value 'A00' caused an error.
The code is still breaking once I hit Z99.
Problem: If the next serial number = Z90 and the user wants to print 35 barcodes I need to stop the operation before it begins and warn the user there are only 10 avail serial numbers remaining
Also, I am also hoping for advice on how I could have accomplished this in a better manner, any advice would be greatly appreciated
Public Shared Function NextSerial(ByVal value As String) As String
Try
If value <= 998 Then
value += 1
Return ZeroPad(value, 3)
End If
Catch ex As Exception
End Try
Const chars As String = "ABCDEFGHJKLMNPQRSTUVWXYZ"
Dim threenumber As String = ZeroPad(value, 3) 'ensure value is 3 digits.
Dim alpha As String = threenumber.Substring(0, 1).ToUpper() ' 1st digit
Dim beta As String = threenumber.Substring(1, 2) 'remaining two digits
Dim newNumber As String
Dim nextletter As String
If beta = "99" Then
beta = "00"
nextletter = chars.Substring((chars.IndexOf(alpha, System.StringComparison.Ordinal) + 1), 1)
newNumber = nextletter + beta
Return newNumber
Else
beta += 1
newNumber = alpha + ZeroPad(beta, 2)
Return newNumber
End If
End Function
Private Shared Function ZeroPad(ByVal number As String, ByVal toLength As Integer) As String
ZeroPad = number
'add the necessary leading zeroes to build it up to the desired length.
Do Until Len(ZeroPad) >= toLength
ZeroPad = "0" & ZeroPad
Loop
End Function
I think you can do this by assuming your first character is the 'hundreds' and converting to a number and incrementing:
Private Function NextSerial(value As String) As String
Const chars As String = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
Dim numericValue As Integer = 100 * (chars.IndexOf(value.Substring(0, 1))) + Integer.Parse(value.Substring(1, 2))
numericValue += 1
Return chars.Substring(numericValue \ 100, 1) + (numericValue Mod 100).ToString.PadLeft(2, "0")
End Function
You should of course perform some error checking at the start of the function to make sure a valid serial number has been handed into the function. I would also put this function into a class and add functions such as isValid, SerialsRemaining and perhaps a function to retrieve a list of multiple serials.
I created constant strings that represent every available character in each digit position. I then used indexing to lookup the positions of the current serial number & moved one number forward to get the next serial. This will always provide the next serial until you run out of numbers.
Note: this code can easily be made more compact, but I left it as-is thinking it might be clearer.
Const charString1 As String = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
Const charString2 As String = "0123456789"
Const charString3 As String = "0123456789"
Public Function NextSerial(ByVal value As String) As String
' ensures the input is three chars long
Dim threenumber As String = Right("000" & value, 3)
Dim char1 As String = threenumber.Substring(0, 1)
Dim char2 As String = threenumber.Substring(1, 1)
Dim char3 As String = threenumber.Substring(2, 1)
Dim char1Pos As Integer = charString1.IndexOf(char1)
Dim char2Pos As Integer = charString2.IndexOf(char2)
Dim char3Pos As Integer = charString3.IndexOf(char3)
If char1Pos = -1 Or char2Pos = -1 Or char3Pos = -1 Then Throw New Exception("Invalid serial number format")
' move to next serial number
char3Pos += 1
If char3Pos > charString3.Length() - 1 Then
char3Pos = 0
char2Pos += 1
End If
If char2Pos > charString2.Length() - 1 Then
char2Pos = 0
char1Pos += 1
End If
If char1Pos > charString1.Length() - 1 Then Throw New Exception("Out of serial numbers!")
Return charString1.Substring(char1Pos, 1) & charString2.Substring(char2Pos, 1) & charString3.Substring(char3Pos, 1)
End Function
I suggest you use integer for all your check and calculation and only convert to serial number for display. It'll be a lot easier to know how many serial number are remaining.
Your serial number is similar to integer except everything over 100 is a letter instead of a number.
Note: It's very important to add error checking, this assumes that all input are valid.
Module Module1
Sub Main()
Console.WriteLine(SerialNumber.ConvertSerialNumberToInteger("D22"))
Console.WriteLine(SerialNumber.ConvertIntegerToSerialNumber(322))
Console.WriteLine(SerialNumber.GetAvailableSerialNumber("Z90"))
For Each sn As String In SerialNumber.GetNextSerialNumber("X97", 5)
Console.WriteLine(sn)
Next
Console.ReadLine()
End Sub
End Module
Class SerialNumber
Private Const _firstPart As String = "ABCDEFGHJKLMNPQRSTUVWXYZ"
Public Shared Function ConvertSerialNumberToInteger(ByVal serialNumber As String) As Integer
Return (_firstPart.IndexOf(serialNumber(0)) * 100) + Integer.Parse(serialNumber.Substring(1, 2))
End Function
Public Shared Function ConvertIntegerToSerialNumber(ByVal value As Integer) As String
Return _firstPart(value \ 100) & (value Mod 100).ToString("00")
End Function
Public Shared Function GetAvailableSerialNumber(ByVal serialNumber As String)
Dim currentPosition As Integer
Dim lastPosition As Integer
currentPosition = ConvertSerialNumberToInteger(serialNumber)
lastPosition = ConvertSerialNumberToInteger("Z99")
Return lastPosition - currentPosition
End Function
Public Shared Function GetNextSerialNumber(ByVal serialNumber As String, ByVal amount As Integer) As List(Of String)
Dim newSerialNumbers As New List(Of String)
Dim currentPosition As Integer
currentPosition = ConvertSerialNumberToInteger(serialNumber)
For i As Integer = 1 To amount
newSerialNumbers.Add(ConvertIntegerToSerialNumber(currentPosition + i))
Next
Return newSerialNumbers
End Function
End Class