Instrução Do...Loop (Visual Basic)Do...Loop Statement (Visual Basic)
Repete um bloco de instruções enquanto uma condição de Boolean
é True
ou até que a condição se torne True
.Repeats a block of statements while a Boolean
condition is True
or until the condition becomes True
.
SintaxeSyntax
Do { While | Until } condition
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
' -or-
Do
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
PartesParts
TermoTerm | DefiniçãoDefinition |
---|---|
Do |
Necessária.Required. Inicia a definição do loop de Do .Starts the definition of the Do loop. |
While |
Necessário a menos que Until seja usado.Required unless Until is used. Repita o loop até que condition seja False .Repeat the loop until condition is False . |
Until |
Necessário a menos que While seja usado.Required unless While is used. Repita o loop até que condition seja True .Repeat the loop until condition is True . |
condition |
Opcional.Optional. Expressão Boolean .Boolean expression. Se condition for Nothing , Visual Basic o tratará como False .If condition is Nothing , Visual Basic treats it as False . |
statements |
Opcional.Optional. Uma ou mais instruções repetidas enquanto, ou até condition , são True .One or more statements that are repeated while, or until, condition is True . |
Continue Do |
Opcional.Optional. Transfere o controle para a próxima iteração do loop de Do .Transfers control to the next iteration of the Do loop. |
Exit Do |
Opcional.Optional. Transfere o controle do loop de Do .Transfers control out of the Do loop. |
Loop |
Necessária.Required. Encerra a definição do loop de Do .Terminates the definition of the Do loop. |
ComentáriosRemarks
Use uma estrutura Do...Loop
quando quiser repetir um conjunto de instruções um número indefinido de vezes, até que uma condição seja satisfeita.Use a Do...Loop
structure when you want to repeat a set of statements an indefinite number of times, until a condition is satisfied. Se você quiser repetir as instruções um número definido de vezes, o para... A próxima instrução é geralmente uma opção melhor.If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice.
Você pode usar While
ou Until
para especificar condition
, mas não ambos.You can use either While
or Until
to specify condition
, but not both.
Você pode testar condition
apenas uma vez, no início ou no fim do loop.You can test condition
only one time, at either the start or the end of the loop. Se você testar condition
no início do loop (na instrução Do
), o loop poderá não ser executado mesmo uma vez.If you test condition
at the start of the loop (in the Do
statement), the loop might not run even one time. Se você testar no final do loop (na instrução Loop
), o loop sempre será executado pelo menos uma vez.If you test at the end of the loop (in the Loop
statement), the loop always runs at least one time.
A condição geralmente resulta de uma comparação de dois valores, mas pode ser qualquer expressão avaliada como um valor de tipo de dados booliano (True
ou False
).The condition usually results from a comparison of two values, but it can be any expression that evaluates to a Boolean Data Type value (True
or False
). Isso inclui valores de outros tipos de dados, como tipos numéricos, que foram convertidos em Boolean
.This includes values of other data types, such as numeric types, that have been converted to Boolean
.
Você pode aninhar loops de Do
colocando um loop dentro de outro.You can nest Do
loops by putting one loop within another. Você também pode aninhar diferentes tipos de estruturas de controle entre si.You can also nest different kinds of control structures within each other. Para obter mais informações, consulte estruturas de controle aninhado.For more information, see Nested Control Structures.
Observação
A estrutura de Do...Loop
oferece mais flexibilidade do que o while... Instrução End While porque ela permite que você decida se deseja encerrar o loop quando condition
parar de ser True
ou quando ele se tornar True
pela primeira vez.The Do...Loop
structure gives you more flexibility than the While...End While Statement because it enables you to decide whether to end the loop when condition
stops being True
or when it first becomes True
. Ele também permite que você teste condition
no início ou no fim do loop.It also enables you to test condition
at either the start or the end of the loop.
Sair doExit Do
A instrução Exit do pode fornecer uma maneira alternativa de sair de um Do…Loop
.The Exit Do statement can provide an alternative way to exit a Do…Loop
. Exit Do
transfere o controle imediatamente para a instrução que segue a instrução Loop
.Exit Do
transfers control immediately to the statement that follows the Loop
statement.
Exit Do
geralmente é usado depois que alguma condição é avaliada, por exemplo, em uma estrutura de If...Then...Else
.Exit Do
is often used after some condition is evaluated, for example in an If...Then...Else
structure. Talvez você queira sair de um loop se detectar uma condição que o torne desnecessário ou impossível para continuar a iteração, como um valor errado ou uma solicitação de encerramento.You might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. Um uso de Exit Do
é testar uma condição que poderia causar um loop infinito, que é um loop que poderia executar um número grande ou mesmo infinita de vezes.One use of Exit Do
is to test for a condition that could cause an endless loop, which is a loop that could run a large or even infinite number of times. Você pode usar Exit Do
para escapar o loop.You can use Exit Do
to escape the loop.
Você pode incluir qualquer número de instruções Exit Do
em qualquer lugar em um Do…Loop
.You can include any number of Exit Do
statements anywhere in a Do…Loop
.
Quando usado em loops de Do
aninhados, Exit Do
transfere o controle do loop mais interno e para o próximo nível mais alto de aninhamento.When used within nested Do
loops, Exit Do
transfers control out of the innermost loop and into the next higher level of nesting.
ExemploExample
No exemplo a seguir, as instruções no loop continuam a ser executadas até que a variável de index
seja maior que 10.In the following example, the statements in the loop continue to run until the index
variable is greater than 10. A cláusula Until
está no final do loop.The Until
clause is at the end of the loop.
Dim index As Integer = 0
Do
Debug.Write(index.ToString & " ")
index += 1
Loop Until index > 10
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
ExemploExample
O exemplo a seguir usa uma cláusula While
em vez de uma cláusula Until
e condition
é testado no início do loop em vez de no final.The following example uses a While
clause instead of an Until
clause, and condition
is tested at the start of the loop instead of at the end.
Dim index As Integer = 0
Do While index <= 10
Debug.Write(index.ToString & " ")
index += 1
Loop
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
ExemploExample
No exemplo a seguir, condition
para o loop quando a variável index
é maior que 100.In the following example, condition
stops the loop when the index
variable is greater than 100. No entanto, a instrução If
no loop faz com que a instrução Exit Do
pare o loop quando a variável de índice é maior que 10.The If
statement in the loop, however, causes the Exit Do
statement to stop the loop when the index variable is greater than 10.
Dim index As Integer = 0
Do While index <= 100
If index > 10 Then
Exit Do
End If
Debug.Write(index.ToString & " ")
index += 1
Loop
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
ExemploExample
O exemplo a seguir lê todas as linhas em um arquivo de texto.The following example reads all lines in a text file. O método OpenText abre o arquivo e retorna um StreamReader que lê os caracteres.The OpenText method opens the file and returns a StreamReader that reads the characters. Na condição de Do...Loop
, o método Peek da StreamReader
determina se há caracteres adicionais.In the Do...Loop
condition, the Peek method of the StreamReader
determines whether there are any additional characters.
Private Sub ShowText(ByVal textFilePath As String)
If System.IO.File.Exists(textFilePath) = False Then
Debug.WriteLine("File Not Found: " & textFilePath)
Else
Dim sr As System.IO.StreamReader = System.IO.File.OpenText(textFilePath)
Do While sr.Peek() >= 0
Debug.WriteLine(sr.ReadLine())
Loop
sr.Close()
End If
End Sub
Consulte tambémSee also
Comentários
Carregando comentários...