2016-10-13 1 views
1

누군가가 "."을 입력 할 때 종료되는 while 루프를 만들려고합니다.vb.net에서 무한 배열을 만드는 방법

Dim x, y As Integer 
    Dim stuff(x) As String 
    y = 1 
    x = 0 
    While y = 1 
     x = x + 1 
     Console.WriteLine("input stuff end with .") 
     stuff(x - 1) = Console.ReadLine() 
     If stuff(x - 1) = "." Then 
      y = 0 
     End If 

    End While 

오류 메시지 : 사전에

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in practise.exe 

Additional information: Index was outside the bounds of the array. 

감사합니다 다음 내가 코드를 다음 오류를 얻을로

내 코드입니다.

+2

시도를 사용 topshot (x)를'바로 당신이 ** X ** – Bugs

+1

사용 목록 대신 배열을 증가 후. – dbasnett

+1

다음은 배열 대신 항목 목록 수가 다를 때 [List'] (https://msdn.microsoft.com/en-us/library/6sh2ey19#Anchor_8)와 같은 제네릭 컬렉션을 사용해야하는 이유 중 하나입니다. http : //stackoverflow.com/a/34453165/1383168. – Slai

답변

0

기본적으로 코드 문제는 배열입니다. 아래 코드는 먼저 크기가 1 인 배열을 정의하는 트릭을 수행 한 다음 루프 내에서 크기 (x + 1)로 배열을 다시 정의 할 수 있습니다.

Dim x, y As Integer 
    Dim stuff(1) As String 
    y = 1 
    x = 0 
    While y = 1 
     x = x + 1 
     Console.WriteLine("input stuff end with .") 
     stuff(x - 1) = Console.ReadLine() 
     If stuff(x - 1) = "." Then 
      y = 0 
     End If 
     ReDim Preserve stuff(x + 1) 

    End While 

희망이

[UPDATE 13/10/16 15시 21분] 어레이에 데이터를 보존 ReDim Preserve-ReDim 변경된 돕는다. 덕분에 'ReDim을 물건을 유지

+1

'Preserve'를 지정하지 않으면 그는 배열에서 데이터를 잃게됩니다 – topshot

+1

감사합니다. @topshot changed answered answer – littleswany

0

당신은 배열 대신 대신 dictionary을 사용할 수 있습니다, 당신은 귀하의 X 변수를 사용할 수 있습니다 키

0
x = x + 1 
ReDim Preserve stuff(x) 'add this line 
Console.WriteLine("input stuff end with .") 

또한 가능성이 잠시 실행 경우 Integer 데이터 유형에 맞게 수있는 초과하는 것입니다. Dim x As Long (또는 더 많은 정보가 필요하면 Decimal).

4

이 목록을

Dim stuff As New List(Of String) 
    Do 
     Console.WriteLine("input stuff end with .") 
     stuff.Add(Console.ReadLine()) 
    Loop While stuff(stuff.Count - 1) <> "." 
관련 문제