I'm having some trouble trying to input integers into an array using visual basic. I'm very new to use visual basic (and programming in general) and I've had a look around google as well as, this website to try and find an answer however I am not finding any luck and I wanted to see if anyone could lend me a hand.
Basically what I have so far
Function inputArray()
Dim array() As Integer
Console.WriteLine("Please input how many integers you would like to add")
For i = 0 To array.Length - 1
Console.WriteLine("Please enter an integer")
Console.ReadLine()
Next
Console.WriteLine(array)
Return array
End Function
What i'm trying to achieve is to ask the user how many integers they would like to input into the array and then allow the user to make an input for the amount of integers they have chosen and to store those integers in the array.
If anyone could possibly give me an example piece of code as to how I would do this or any help at all I would really appreciate it.
You could use a List
instead of an Array
.
This is a short example (without error-handlings)
Imports system.Threading
Module Module1
Sub Main()
Module1.BuildIntegerList()
Console.ReadKey()
Environment.Exit(exitCode:=0)
End Sub
Private Sub BuildIntegerList()
Dim values As New List(Of Integer)
Dim amount As Integer
Dim nextValue As Integer
Console.WriteLine("Please input how many integers you would like to add")
amount = CInt(Console.ReadKey().KeyChar.ToString())
Do Until values.Count = amount
Console.Clear()
Console.WriteLine("Please enter an integer")
nextValue = CInt(Console.ReadKey().KeyChar.ToString())
values.Add(nextValue)
Thread.Sleep(250)
Loop
Console.Clear()
Console.WriteLine(String.Format("Values: {0}", String.Join(", ", values)))
End Sub
End Module
I would also use List as mentioned by ElektroStudios. However, since you used arrays, here's how I would write it.
Function inputArray()
Console.WriteLine("Please input how many integers you would like to add")
Dim count = CInt(console.ReadLine())
Dim array(count-1) As Integer
For i = 0 To count - 1
Console.WriteLine("Please enter an integer")
array(i) = CInt(Console.readline())
Next
For i = 0 To array.Length-1
Console.Write(array(i))
Next
return array
End Function
Here is a working example : dotnetfiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.