在未排序的数组中插入项目

时间:2014-10-08 14:31:25

标签: arrays vb6

请帮我解决这个问题。我在vb6中创建一个数组程序,其过程就像这样

  • 输入数组大小:3
  • 输入数组元素:1
  • 2
  • 3
  • 输入插入位置:2
  • 输入要插入的项目:5
插入后

  • 1
  • 5
  • 2
  • 3

这是我已经做过的代码

Dim a(50) As Integer, n As Integer, loc As Integer, item As Integer, x As Integer

Private Sub Form_Load()
  Dim i As Integer
  n = InputBox("Enter Size of an Array: ", "Size")
  Text1.Text = ""
  For i = 1 To n
    a(i) = InputBox("Enter Elemets of an Array: ", "Elements")
  Next i
  location = InputBox("Enter Location of Insertion: ", "Location")
  item = InputBox("Enter Item to Insert: ", "Item")

  unsorted

  For i = 1 To n
    Text1.Text = Text1.Text + "" & a(i)
    list1.AddItem Text1.Text
    Text1.Text = ""
  Next i
End Sub

Public Sub unsorted()
  While i >= (location - 1)
    a(i + 1) = a(i)
    i = i + 1
  Wend
  a(location - 1) = item
  n = n + 1
End Sub

我在while循环中有错误。请帮帮我

2 个答案:

答案 0 :(得分:1)

类似的东西:

Option Explicit

Private Sub Command1_Click()
  Dim intLoop As Integer
  Dim intA() As Integer
  ReDim intA(2) As Integer
  Dim intIndex As Integer
  Dim intVal As Integer
  intA(0) = 1
  intA(1) = 2
  intA(2) = 3
  intIndex = 2
  intVal = 5
  intA = InsertVal(intA, intIndex, intVal)
  For intLoop = 0 To UBound(intA)
    Print CStr(intLoop) & " : " & CStr(intA(intLoop))
  Next intLoop
End Sub

Private Function InsertVal(intSrc() As Integer, intIndex As Integer, intVal As Integer) As Integer()
  Dim intLoop As Integer
  Dim intAdded As Integer
  Dim intResult() As Integer
  ReDim intResult(UBound(intSrc) + 1)
  intAdded = 0
  For intLoop = 0 To UBound(intSrc)
    If intLoop = intIndex Then
      intResult(intIndex) = intVal
      intAdded = intAdded + 1
    End If
    intResult(intLoop + intAdded) = intSrc(intLoop)
  Next intLoop
  InsertVal = intResult
End Function

答案 1 :(得分:1)

我自己已经解决了这个问题

Dim a(50) As Integer
Dim n As Integer
Dim location As Integer
Dim item As Integer

Private Sub Command1_Click()
List1.Clear
Call Form_Load
End Sub

Private Sub Form_Load()
Dim i As Integer
On Error Resume Next
Form1.Show
n = InputBox("Enter Size of an Array: ", "Input")
If n > 50 Then
    MsgBox "The maximum size of array is 50!", vbCritical, "Error"
    Exit Sub
End If
    For i = 1 To n
        a(i) = InputBox("Enter Elements of an array: ", "Input")
    Next i

        location = InputBox("Enter Location of insertion: ", "Input")
    If location > n Then
        MsgBox "Error! Location not possible!", vbCritical, "Warning"
        Exit Sub
    End If
        item = InputBox("Enter Item to insert: ", "Input")

insert_unsorted

'print
    For i = 1 To n
    Text1.Text = Text1.Text + "" & a(i)
    List1.AddItem Text1.Text
    Text1.Text = ""
Next i

End Sub

Public Sub insert_unsorted()
Dim i As Integer
i = n

Do While i >= location - 1
    a(i + 1) = a(i)
    i = i - 1

Loop
    a(location) = item
    n = n + 1
End Sub

非常感谢