So i want to perform some code N times. N is textbox's value (e.g: 12).
I have no idea how to accomplish this, but something like this is on my mind:
For Each i as 1 in textbox1.text
'some code
Next
or
dim num1 as integer = 0
While num1 < textbox1.text
'some code
num1 += 1
Next
Those were just some ideas that were on my mind when i though about this question, none of above is tested nor tried to code.
Any ideas?
First and foremost, turn on Option Strict. This will save you time in the long run by converting possible runtime errors into compiler errors. At the top of the code file:
Option Strict On
It can also be set for the entire project:
Project Properties -> Compile Tab -> Option Strict selector: On
You can also make it the default for all new projects via:
Tools -> Options -> Projects and Solutions -> VB Defaults
What it Does
TextBox.Text always contains text (hence the clever names). "12" is just a string and is not the same as 12. So, before you can use it, you need to convert from string to integer. Note: If you want to restrict user input to numbers consider using a NumericUpDown.
There are several ways to convert, but considering that the data comes from a user, we have to allow that they may enter "I like pie" instead of numerals. So, we want to use the safest method which in this case is Integer.TryParse:
' declare int var to hold the result
Dim LoopCount As Integer
If Integer.TryParse(TextBox132.Text, LoopCount) Then
' success! LoopCOunt contains the integer value of the Text control
For n As Integer = 0 To LoopCount - 1
' some code to do something
Next
Else
' failed - scold the user with a MessageBox
End if
The comments in the code explain, but first you declare an integer variable to hold the converted value. Integer.TryParse is a function which will return True/False. If it succeeds, your variable will hold the integer value.
See Converting DataTypes for Option Strict for other convert methods and cases where they are appropriate.
This might work, I haven't tried:
Dim repeat_times as Integer = 0
Do Until repeat_times = 10 'times you want to repeat
repeat_times = repeat_times + 1
Console.WriteLine("Hello World") 'or anything you want
Loop
For n As Int32 = 0 To TextBox1.text - 1 was an answer for my question.
Related
Currently I have these data inside my textfile.txt:
I want to split them up into a 2D array when a comma is met. How do I do so?
This is my code for now. Please do point out the mistakes I made.
Dim priceArray(5, 2) As String
Dim i, j As Integer
Dim data As String
Dim oilpriceFile As System.IO.StreamReader
oilpriceFile = New System.IO.StreamReader("C:\Users\zack\OneDrive\Desktop\oilprice.txt")
For i = 0 To UBound(priceArray)
data = oilpriceFile.ReadLine()
For j = 0 To UBound(priceArray)
priceArray(i, j) = data.Split(",") //there's an error stating "value of type string() cannot be converted into string"
j = j + 1
Next
i = i + 1
Next
There are several things you are doing incorrectly.
First turn on Option Strict in the Project Properties and also under Options on the Tools menu.
You do not declare the increment variables used in For loops.
StreanReader needs to be disposed. You should know this because you always check the documentation before you use an unfamiliar framework class. When you do this you will see a Dispose method. When you see this, it needs to be called when you are through with using it. See Using...End Using.
You don't have to deal with Dispose if you use File.ReadAllLines(). This returns an array of the lines in the file.
A For loop increments the value of the first variable automatically. You do not increment it explicitly or you will skip values.
You have defined a 2 dimensional array. When you call UBound on the array, which dimension are you calling it on?? You must indicate which dimension you are asking about.
UBound(priceArray, 1) and UBound(priceArray, 2)
Where 1 and 2 designate the dimension you are getting.
This is the old vb6 way to get this value. The .net framework provides GetUpperBound() for the same purpose. This method uses the .net zero based rank where GetUpperBound(0) will return upper bound of the first dimension of the array.
The next problem is the use of Spilt. Split returns an array of strings and you are trying to assign it to a single string. It takes a Char as a parameter. You have passed a String. To tell the compiler that you intend a Char follow the String by a lower case c.
A side note. // is the comment indicator in C#. In vb.net use the single quote '.
Private Sub OPCode()
Dim priceArray(5, 2) As String
Dim lines = File.ReadAllLines("C:\Users\zack\OneDrive\Desktop\oilprice.txt")
For i = 0 To priceArray.GetUpperBound(0)
Dim data = lines(i)
Dim splits = data.Split(","c)
For j = 0 To priceArray.GetUpperBound(1)
priceArray(i, j) = splits(j)
Next
Next
End Sub
basically, I want to reverse the numbers. (in the textbox there will be only 2-digit numbers)
if I have Textbox1.text:
12
2
41
71
70
I want to display in the box (Textbox1.text)
21
2
14
17
70
Function:
Public Shared Function Reverse(num As Integer) As Integer
Dim _reverse As Integer = 0
While num <> 0
_reverse *= 10
_reverse += num Mod 10
num \= 10
End While
Return _reverse
End Function
it should work, it actually works, but I don't know how to arrange it to work in all lines.
For Each lines In TextBox1.Lines
Dim rev = Reverse(lines)
lines.Replace(lines, rev)
Next
This is a perfect example of what happens when people try to write code without knowing what the code is supposed to. What the code is supposed to do is not just the end result but the steps to get there. If you don't know what the steps are then you shouldn't be writing any code because it's unlikely that what you write will do anything useful. Code is simply an implementation of logic so you should be getting the logic down first. It doesn't take any programming experience to work out the logic because we could all do this if it was a manual process and that would be the same logic.
So, what are the steps involved?
Get the lines of the text.
Loop over the lines.
Reverse the current line.
Replace the original line with the result of reversing.
Replace the text with the complete results.
If you actually consider each of those steps, it should be obvious that you cannot use a For Each loop because that will only let you get data out of a list, not put data into it. That would make it obvious that a For loop is the right choice, because will let you get data out and put it in. Now you can write code that actually does something useful.
Dim lines = TextBox1.Lines
For i = 0 To lines.GetUpperBound(0)
Dim line = lines(i)
Dim number = CInt(line)
Dim result = Reverse(number)
lines(i) = result.ToString()
Next
TextBox1.Lines = lines
Simple stuff but, again, if you don't know what the code has to actually do, writing code to do it is a challenge. Always break the problem down into smaller parts first, so you can work on each part individually, and always work out the logic you're trying to implement - and test that logic manually - before trying to write code to implement it.
In my code,I have now realised I have to use the New Random function, my code was working before with the Randomize and then the numbers but now it comes up with loads of errors and wont even let me run the program. I think it is only a small error but I just need some help to get the final bit going
Heres the code and thanks for any help :)
I cannot get the code to work with the randomly generated number and I have to use the New Random function I cannot use randomize() Does anybody know how to help here is the code.
Dim timestook As Int32 = 1
Dim usersguess As Integer
Dim value = New Random(0 - 19)
Console.WriteLine("You have to guess this number. It is between 1 and 20. Good Luck !")
usersguess = Console.ReadLine()
'keep looping until they get the right value
While usersguess <> value
'now check how it compares to the random value
If usersguess < value Then
timestook = timestook + 1
Console.WriteLine("You're too low. Go higher ")
ElseIf usersguess > value Then
Console.WriteLine("You're too high. Go Lower.")
timestook = timestook + 1
End If
'If they are wrong the code will run again,after telling the user if they are too high or too low.
usersguess = Console.ReadLine()
End While
' Console.WriteLine("You're correct. Well Done")
If usersguess = value Then
Console.WriteLine("You took,{0}", timestook)
End If
Console.ReadLine()
End Sub
You'll want to do some googling on how to use random numbers. Your problem is that you aren't creating a Random object to handle the random number generation.
Here's how you can fix your code:
Dim randNumGen As New Random() 'Create Random object
Dim value As Integer = randNumGen.Next(0, 20) 'set value equal to a new random number between 0-19
Please note that this code could be further refactored for readability and simplicity (like changing timestook = timestook + 1 to timestook += 1 and selecting better variable names like numberOfGuesses as opposed to timestook, etc.
The expression New Random(0-19) does not do at all what you think it does, name it does NOT return an integer. Instead, it creates an instance of a Random object, which is a type that knows how to create new random values. The 0-19 part of the expression is the seed for the Random object's constructor, and is the same as just passing the value -19.
This looks like it's either homework or personal practice, so I feel like you will be better served in this case with a separate example using the Random type for reference than you would if I fixed the code sample in the question for you:
Dim rnd As New Random()
For i As Integer = 0 To 10
Console.WriteLine(rnd.Next(0, 20))
Next i
It's also worth mentioning here that you typically only want one Random object for your entire program, or at least only one Random object for each logical part of your program. Creating new Random objects resets the seeds, and for best results you want to follow the same seed on subsequent calls to the same instance for a while.
Is it possible to convert, say, a textbox input to working code?
For example, user types 'if x<10 then y=2 else y=5' into textbox1, it gets used directly as code something like ...
dim x as integer = 5
dim y as integer = 0
include processed textbox1.text
resultbox.text = (y*20).tostring
It's not important why this would be needed - just whether there is any straight-forward method that parses a string to code.
Many thanks.
Maybe this is what you are looking for:
http://www.codeproject.com/Articles/12852/Compile-and-Run-VB-NET-Code-using-the-CodeDom
yes you can do this using the VBCodeProvider class. Although the amount of code required is quite significant:
http://www.codeproject.com/Articles/5472/Compiling-NET-code-on-the-fly
I have this bit of code that is being converted from vb6 to vb.net. I need to know what LenB is doing in this bit of code.
Dim singleValue As Single 'var for conversion use(4byte -> 1single)'
Dim bytes() As Byte
Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size'
For n = 0 To CDbl(ItemNumberCombo.Text) - 1
'bytes() -> single'
'UPGRADE_ISSUE: LenB function is not supported.'
ReDim bytes(LenB(singleValue) - 1)
bytes(3) = valueB(n * 4)
bytes(2) = valueB(n * 4 + 1)
bytes(1) = valueB(n * 4 + 2)
bytes(0) = valueB(n * 4 + 3)
'UPGRADE_ISSUE: LenB function is not supported.'
'UPGRADE_ISSUE: VarPtr function is not supported. '
Call memcpy(VarPtr(singleValue), VarPtr(bytes(0)), LenB(singleValue))
'display the result'
DText(n).Text = VB6.Format(singleValue, "0.000000E+00") 'CStr(singleValue)'
If DataSaveCheckBox.CheckState = 1 And FileNameText.Text <> "" Then
csvOutput = csvOutput & DText(n).Text & ","
End If
Next n
Am I right in thinking that bytes is always ReDim'ed to the same size? By the looks of it 4 elements.
Why then use LenB to ReDim if you could just use a number? And why ReDim in the loop at all?
LenB() returns the length in bytes of a variable. The most common example is for strings, where it returns the size of the string in bytes rather than the number of characters, regardless of character encoding. For other types it returns the size of an object- the size of a single being 4. The reason they would do this is that they wanted the code to survive if a future version of visual basic ever changed the size of a single (never mind hard-coding the number 4 when assigning to the byte array).
When upgrading LenB() to .Net, for strings use System.Text.Encoding.Unicode.GetBytes() to get an array already populated with your string text bytes. Remember that .Net always uses Unicode for strings internally. If you really need a different encoding there are a number of alternatives in the Encoding namespace. For other types use the BitConverter class. Either way, don't go line by line as the newer methods take away a lot of the busy work.
Here — I'll help you out with the conversion some:
(earlier)
Dim csvOutput As New StringBuilder()
(later)
Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size'
Dim singleValue As Single 'var for conversion
' Included because the original developer was concerned the size of a single could change
Dim singleSize As Integer = BitConverter.GetBytes(singleValue).Length
Dim NumberItems As Double
If Double.TryParse(ItemNumberCombo.Text, NumberItems) Then
For n As Integer = 0 To NumberItems - 1
singleValue = BitConverter.ToSingle(valueB, n * singleSize)
'display the result
DText(n).Text = singleValue.ToString("E6") 'CStr(singleValue)
If DataSaveCheckBox.CheckState = 1 AndAlso Not String.IsNullOrEmpty(FileNameText.Text) Then
csvOutput.Append(DText(n).Text & ",")
End If
Next n
Else
' Handle Invalid ComboBox value here- may not be an issue for you
End If
Note that this code also demonstrates a StringBuilder as a much better way to build your csv data, the AndAlso operator, the .TryParse() methods, String.IsNullOrEmpty(), and Standard Format Strings, all of which are intended to replace constructs or techniques from vb6.
Trying to explain bad code... is just an effort in futility.
Interesting way to fill a Single by loading a byte array.
The LenB function gives you the length in bytes of a variable.
Yes it will always return 4 when passed a Single variable type.
My guess for the redim is so the array gets initialized instead of preserved.
But since it then assigns all 4 bytes, it isn't technically needed and is probably just defensive programming. Defensive programming might also explain the LenB. In case Single changes size in the future.