How to do this in Visual basic? - vb.net

How to do the "a++" and "b++" in Visual basic?
What is the another codes for there in Vb?
The names there are just example.
int a = 0;
int b = 0;
{
if (ans1.Text == "James")
{
a++;
}
else
{
b++;
}
if (ans2.Text == "Ryan")
{
a++;
}
else
{
b++;
}
if (ans3.Text == "Mac")
{
a++;
}
else
{
b++;
}
t1.Text = a.ToString();
t2.Text = b.ToString();
}

Like this:
a += 1
b += 1
(...)

Like this
DIM a as integer = 0
DIM b as integer = 0
If ans1.Text = "James" Then
a += 1
Else
b += 1
End If
If ans2.Text = "Ryan" Then
a += 1
Else
b += 1
End If
If ans3.Text = "Mac" Then
a += 1
Else
b += 1
End If
t1.Text = a.ToString()
t2.Text = b.ToString()

Your question has already been answered but I think it would be useful to see how you could simplify your code:
Dim correctAnswers As Integer = 0
Dim totalQuestions As Integer = 3'you need to modify this is you add more questions
'increment the number of correct answers for each one we find
correctAnswers += If(ans1.text = "James", 1, 0)
correctAnswers += If(ans2.text = "Ryan", 1, 0)
correctAnswers += If(ans3.text = "Mac", 1, 0)
'show the number of correct and incorrect answers
t1.Text = correctAnswers.ToString()
t2.Text = (totalQuestions - correctAnswers).ToString() 'show the number of incorrect questions

Neither the postfix nor prefix ++ are defined in Visual Basic.
Your only realistic option is to use a = a + 1 (or, in later BASICs, a += 1) instead (note the lack of a ; for a statement terminator). But note that this will not evaluate to the previous value of a and the entire construct is not an expression in the C / C++ sense. You could build a function to mimic a++ but that would be too obfuscating.

Related

i want to use Regex.IsMatch to find TB, GB, MB in VB.net Visual Basic

I have a textbox which i need to validate for the below entries and also need to replace
"3 GB" valid input
"3.2 GB" valid input
"3.2GB" valid input >> then replace as "3.2 GB"
"3.2" invalid input, ask for follow correct format MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
"VGGGB" invalid input, ask for follow correct format MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Sub Main()
Dim input = Console.ReadLine().ToUpper()
Dim nInput, value
Dim ChkDecimal As Double
If input IsNot "" Then
If input.EndsWith("TB") Then
nInput = input.Replace("TB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1048576 + 1)
ChkDecimal = FormatNumber(CDbl(value / 1048576), 2) Mod 1 ' check the number has a valid Decimal value
If ChkDecimal = 0 Then
Console.WriteLine(FormatNumber(CDbl(value / 1048576), 0) & " TB")
Else
Console.WriteLine(FormatNumber(CDbl(value / 1048576), 2) & " TB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
ElseIf (input.EndsWith("GB")) Then
nInput = input.Replace("GB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1024)
ChkDecimal = FormatNumber(CDbl(value / 1024), 2) Mod 1 ' check the number has a valid Decimal value
If ChkDecimal = 0 Then
Console.WriteLine(FormatNumber(CDbl(value / 1024), 0) & " GB")
Else
Console.WriteLine(FormatNumber(CDbl(value / 1024), 2) & " GB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
ElseIf input.EndsWith("MB") = True Then
nInput = input.Replace("MB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1)
Console.WriteLine(FormatNumber(CDbl(value * 1), 0) & " MB")
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
Else
Console.WriteLine("Capacity input Format: 99.99 MB/GB/TB")
End If
End Sub
I wouldn't use a regular-expression for this, because there's a much simpler (and more robust!) approach described below.
If you do use a regular-expression, you'll need to add all of the unit names to the expression, which is painful. Regular-expressions are not well-suited to accepting a large list of possible literal inputs.
Using a regular-expression would also mean the input would not be culture-aware, which is bad for usability (as many places around the world swap the , and . glyphs in numbers) - and you really don't want to handle things like digit-grouping, etc.
Instead, first extract and validate the unit name, then parse the numeric value using Decimal.TryParse
Like so (using C# because it's 2am here and I'm not getting paid to write this answer):
void Example()
{
String textBoxValue = "3 GB";
if( TryParseBinaryDataQuantity( textBoxValue, out Int64 valueBytes ) )
{
MessageBox.Show( "Visual Basic is dead." );
}
else
{
MessageBox.Show( "Input is not a valid binary data quantity." );
}
}
public static Boolean TryParseBinaryDataQuantity( String input, out Int64 valueBytes )
{
input = ( input ?? "" ).Trim();
if( input.Length < 3 ) // input is too short to be meaningful.
{
valueBytes = default;
return false;
}
// Extract the unit-name by taking the last 3 characters of the input string and trimming any whitespace (this isn't the most robust or correct approach, but I'm feeling lazy):
String unitName = input.Substring( startIndex: input.Length - 3 );
// Validate the unit-name and get the bytes multiplier:
if( !TryParseBinaryDataUnit( unitName, out Int64 multiplier ) )
{
valueBytes = default;
return false;
}
// Consider repeating the above but for the last 2 characters of the string in order to match input like "3GB" instead of "3GiB" and "3 GB" and "3 GiB".
// Parse and multiply:
String numberPart = input.Substring( startIndex: 0, length: input.Length - 3 );
if( Decimal.TryParse( numberPart, NumberStyles.Any, CultureInfo.CurrentCulture, out Decimal quantity )
{
Decimal bytesValue = quantity * multiplier;
// Fail if the bytesValue is non-integral or negative:
if( bytesValue != Math.Floor( bytesValue ) || bytesValue < 0 )
{
valueBytes = default;
return false;
}
return (Int64)bytesValue;
}
}
private static Boolean TryParseBinaryDataUnit( String unitName, out Int64 equivalentBytes )
{
if( "GB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024 * 1024; // or 1000 * 1000 * 1000 depending on if you're differentiating between GiB and GB.
return true;
}
else if( "GiB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024 * 1024;
return true;
}
else if( "MiB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024;
return true;
}
else if( "MB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024;
return true;
}
else if( "KB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024;
return true;
}
else if( "KB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024;
return true;
}
else
{
equivalentBytes = default;
return false;
}
}
I will recommend you to use proper library to parse the given input. I have used one in past for doing this (https://github.com/omar/ByteSize)
Here is quick example of how you can do this. I know there must be better way to do this but this would do the job =)
var input = Console.ReadLine();
input = input.ToLower();
var reg = Regex.Match(input, "([\\d\\.]+)");
if (reg.Success && double.TryParse(reg.Groups[1].Value, out double rawSize))
{
if (input.EndsWith("tb"))
Console.WriteLine(ByteSize.FromTeraBytes(rawSize));
else if (input.EndsWith("gb"))
Console.WriteLine(ByteSize.FromGigaBytes(rawSize));
else if (input.EndsWith("mb"))
Console.WriteLine(ByteSize.FromMegaBytes(rawSize));
else if (input.EndsWith("kb"))
Console.WriteLine(ByteSize.FromKiloBytes(rawSize));
}
Input> 1234.56mb
Output> 1.23 GB
You can try my method as following:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'1.3 GB
'1.3gb
'1gb
Console.WriteLine("Pleasen input your entry:")
Dim str As String = TextBox1.Text
Dim str1 As String = str.Substring(str.Length - 2, 2)
If str1.ToUpper = "TB" Or str1.ToUpper = "GB" Or str1.ToUpper = "MB" Then
Dim str2 As String = str.Remove(str.Length - 2)
Dim str3 As String = str.Substring(str2.Length - 1, 1)
If str3 = " " Then
Dim str4 As String = str.Remove(str.Length - 3)
If Regex.IsMatch(str4, "^\d*[.]?\d*$") Then
MsgBox("valid input")
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
Else
If Regex.IsMatch(str2, "^\d*[.]?\d*$") Then
TextBox1.Text = str.Insert(str.Length - 2, " ")
MsgBox("valid input")
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
End If
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
End Sub
End Class

Fingerprint Hardware ID GetHexString

I found a fingerprint class in C# here
I'm trying to convert the function below to VB .NET but I am having issues with the line that reads s+ = (char)....Any help would be appreciated.
private static string GetHexString(byte[] bt)
{
string s = string.Empty;
for (int i = 0; i < bt.Length; i++)
{
byte b = bt[i];
int n, n1, n2;
n = (int)b;
n1 = n & 15;
n2 = (n >> 4) & 15;
if (n2 > 9)
s += ((char)(n2 - 10 + (int)'A')).ToString();
else
s += n2.ToString();
if (n1 > 9)
s += ((char)(n1 - 10 + (int)'A')).ToString();
else
s += n1.ToString();
if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
}
return s;
}
Is there a better way to write this function in VB.NET?
This
s += ((char)(n1 - 10 + (int)'A')).ToString();
is the same as
s &= Chr((n1 - 10 + Asc("A")))

multidimensional array linq query

i have 5 dimensional array, when using linq to query, the results are sorted in dimensional way:
array(a)(b)(c)(d)(e) , dimension = 1
using for next:
For e = 0 To dimension - 1
For d = 0 To dimension - 1
For c = 0 To dimension - 1
For b = 0 To dimension - 1
For a = 0 To dimension - 1
listbox.Items.Add(array(a, b, c, d, e).disc)
Next
Next
Next
Next
Next
this would result in:
abcde
00000
10000
01000
...
if i use linq:
listbox.Items.AddRange((From item In array Select item.disc).ToArray)
this would result in:
abcde
00000
00001
00010
...
how can i achieve the first result with linq?
Public Class ArrayExt
Public Shared Function GetFirstFastestEnumerator(Of T)(source As Array) As IEnumerable(Of T)
Dim srcRank = source.Rank
Dim indices = New Integer((srcRank) - 1) {}
Dim len = source.Length
For i = 0 To srcRank - 1
indices(i) = source.GetLowerBound(i)
Next
Dim curRank As Integer = 0
For i = 0 To len - 1
Return CType(source.GetValue(indices), T)
While (curRank < srcRank)
If (indices(curRank) < source.GetUpperBound(curRank)) Then
indices(curRank) = indices(curRank) + 1
curRank = 0
Exit While
Else
indices(curRank) = source.GetLowerBound(curRank)
curRank = curRank + 1
End If
End While
Next
End Function
End Class
You need a custom Iterator to go through the array in the rank order you want, which is opposite the built-in order.
public static class ArrayExt {
public static IEnumerable<T> GetFirstFastestEnumerator<T>(this Array src) {
var srcRank = src.Rank;
var indices = new int[srcRank];
var len = src.Length;
for (var j1 = 0; j1 < srcRank; ++j1)
indices[j1] = src.GetLowerBound(j1);
int curRank = 0;
for (var j1 = 0; j1 < len; ++j1) {
yield return (T)src.GetValue(indices);
while (curRank < srcRank) {
if (indices[curRank] < src.GetUpperBound(curRank)) {
++indices[curRank];
curRank = 0;
break;
}
else {
indices[curRank] = src.GetLowerBound(curRank);
++curRank;
}
}
}
}
}
Which you can use either with LINQ or foreach. Replace arrayType with the class stored in array.
listbox.Items.AddRange((From item In array.GetFirstFastestEnumerator<arrayType>() Select item.disc).ToArray)
Or Visual Basic version:
Public Module Ext
<Extension()> _
Public Iterator Function GetFirstFastestIterator(Of T)(source As Array) As IEnumerable(Of T)
Dim srcRank = source.Rank
Dim indices = New Integer((srcRank) - 1) {}
Dim len = source.Length
For i = 0 To srcRank - 1
indices(i) = source.GetLowerBound(i)
Next
Dim curRank As Integer = 0
For i = 0 To len - 1
Yield CType(source.GetValue(indices), T)
While (curRank < srcRank)
If (indices(curRank) < source.GetUpperBound(curRank)) Then
indices(curRank) = indices(curRank) + 1
curRank = 0
Exit While
Else
indices(curRank) = source.GetLowerBound(curRank)
curRank = curRank + 1
End If
End While
Next
End Function
End Module

Splitting a String into Pairs

How would I go on splitting a string into pairs of letter in VB?
for example: abcdefgh
split into: ab cd ef gh
I'll throw my hat in the ring:
Dim test As String = "abcdefgh"
Dim results As New List(Of String)
For i As Integer = 0 To test.Length - 1 Step 2
If i + 1 < test.Length Then
results.Add(test.Substring(i, 2))
Else
results.Add(test.Substring(i))
End If
Next
MessageBox.Show(String.Join(" ", results.ToArray))
The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.
Dim src As String = "abcdef"
Dim size As Integer
If src.Length > 0 Then
If src.Length Mod 2 = 0 Then
size = (src.Length / 2) - 1
Else
size = ((src.Length + 1) / 2) - 1
End If
Dim result(size) As String
For i = 0 To src.Length - 1 Step 2
If i = src.Length - 1 Then
result(i / 2) = src.Substring(i, 1)
Else
result(i / 2) = src.Substring(i, 2)
End If
Next
End If
In C# you would do like this:
Dictionary<String, String> Split(String input)
{
if (input.Count % 2 == 0)
{
Dictionary<string, string> Pairs = new Dictionary( );
for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
{
Char
Left = input[L],
Right = input[R];
Pairs.Add(
Left.ToString(),
Right.ToString());
}
}
else
{
throw new NotEvenException( );
}
return Pairs( );
}
void Main()
{
var Pairs = Split("ABCDEFGH");
foreach(string Key in Split("ABCDEFGH"))
{
Console.Write("{0}{1}\n", Key, Pairs[Key]);
}
}
/*
Output:
AB
CD
EF
GH
*/
Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.
Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.
For example: The method Count (of the object String) exists in both C# and in VB.
Hope it helps a bit at least!

permutations gone wrong

I have written code to implement an algorithm I found on string permutations. What I have is an arraylist of words ( up to 200) and I need to permutate the list in levels of 5. Basically group the string words in fives and permutated them. What I have takes the first 5 words generates the permutations and ignores the rest of the arraylist?
Any ideas appreciated.
Private Function permute(ByVal chunks As ArrayList, ByVal k As Long) As ArrayList
ReDim ItemUsed(k)
pno = 0
Permutate(k, 1)
Return chunks
End Function
Private Shared Sub Permutate(ByVal K As Long, ByVal pLevel As Long)
Dim i As Long, Perm As String
Perm = pString ' Save the current Perm
' for each value currently available
For i = 1 To K
If Not ItemUsed(i) Then
If pLevel = 1 Then
pString = chunks.Item(i)
'pString = inChars(i)
Else
pString = pString & chunks.Item(i)
'pString += inChars(i)
End If
If pLevel = K Then 'got next Perm
pno = pno + 1
SyncLock outfile
outfile.WriteLine(pno & " = " & pString & vbCrLf)
End SyncLock
outfile.Flush()
Exit Sub
End If
' Mark this item unavailable
ItemUsed(i) = True
' gen all Perms at next level
Permutate(K, pLevel + 1)
' Mark this item free again
ItemUsed(i) = False
' Restore the current Perm
pString = Perm
End If
Next
K above is = to 5 for the number of words in one permutation but when I change the for loop to the arraylist size I get an error of index out of bounds
Index out of bounds error usually happens when you start the loop from 1 to length. The the for loop as following.
For i = 0 to array.length - 1
You will get this error.
When you do
For i = 1 To K
The last value of i will be the size of your array.
chunks.Item(i)
Will crash when i equals the size of the array since the index starts at 0.
I would suggest you change your for loop to
For i = 0 To K - 1
Or you change the way you access the values in your arrays to
chunks.Item(i-1)
C++ Permutation
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0)
{
for (int i = 0; i < size; i++)
{
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void permute(int *v, const int start, const int n)
{
if (start == n-1) {
print(v, n);
}
else {
for (int i = start; i < n; i++) {
int tmp = v[i];
v[i] = v[start];
v[start] = tmp;
permute(v, start+1, n);
v[start] = v[i];
v[i] = tmp;
}
}
}
main()
{
int v[] = {1, 2, 3, 4};
permute(v, 0, sizeof(v)/sizeof(int));
}