Home> Java> javaTutorial> body text

The do-while loop in Java

王林
Release: 2024-07-17 14:08:58
Original
892 people have browsed it

O Laço do-while em Java

General Structure

The do-while loop executes the statements at least once before checking the condition.

The general form is:

do { instruções; } while(condição);
Copy after login
e

Difference between for and while loops

  • In for and while, the condition is checked before executing the loop.
  • In do-while, the condition is checked after the loop executes, ensuring that it executes at least once.

Simple Example

A program that loops until the user enters the letter 'q':

// Demonstra o laço do-while. class DWDemo { public static void main(String args[]) throws java.io.IOException { char ch; do { System.out.print("Press a key followed by ENTER: "); ch = (char) System.in.read(); // obtém um char } while(ch != 'q'); } }
Copy after login
e

Improved Guessing Game

A guessing program that loops until the user guesses the correct letter:
see Guess4.java

Explanation of the Divination Program

  • The program reads characters from the user until the correct letter is guessed.
  • There are two do-while loops:
  • The first loop continues until the user guesses the correct letter.
  • The second loop discards extra characters from the input buffer until it encounters an n (newline).

Execution Example

Typical execution of the guessing program

I'm thinking of a letter between A and Z. Can you guess it: A ...Sorry, you're too low Try again! I'm thinking of a letter between A and Z. Can you guess it: Z ...Sorry, you're too high Try again! I'm thinking of a letter between A and Z. Can you guess it: K ** Right **
Copy after login
e

Important Detail

  • Console input is stored in a line buffer, so pressing ENTER adds a newline sequence that needs to be discarded.
  • The second do-while loop removes extra characters from the buffer to avoid unwanted reads.

Conclusion

  • The do-while loop is useful when you need to ensure that the block of statements is executed at least once.
  • It is especially practical for user interactions where initial action is required before checking the condition.

The above is the detailed content of The do-while loop in Java. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!