Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Challenge: Building a Server Retry Mechanism | Loops
Java Basics (unit tests)
course content

Kursinnehåll

Java Basics (unit tests)

Java Basics (unit tests)

1. Getting Started
2. Basic Types and Operations
3. Loops
4. Arrays
5. String

book
Challenge: Building a Server Retry Mechanism

Uppgift

Swipe to start coding

Implement a program that attempts to connect to a server up to 5 times. If the connection is successful, the program prints a success message. If it fails after 5 attempts, it prints an error message.

  1. Create a method called tryConnect(int successfulAttempt) that returns a boolean indicating whether the connection succeeded.
  2. Inside this method:
    • Start a do-while loop that runs up to 5 times.
    • On each iteration, increment the retry counter.
    • If the retry count equals the given successfulAttempt, print a success message and return true.
    • If not, print "Server unavailable, retrying...".
  3. If the loop finishes without success, return false.
  4. In the main method, call tryConnect(...) with a test value and print "Failed to connect to the server after 5 attempts." if the result is false.

Lösning

java

solution

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4
toggle bottom row

book
Challenge: Building a Server Retry Mechanism

Uppgift

Swipe to start coding

Implement a program that attempts to connect to a server up to 5 times. If the connection is successful, the program prints a success message. If it fails after 5 attempts, it prints an error message.

  1. Create a method called tryConnect(int successfulAttempt) that returns a boolean indicating whether the connection succeeded.
  2. Inside this method:
    • Start a do-while loop that runs up to 5 times.
    • On each iteration, increment the retry counter.
    • If the retry count equals the given successfulAttempt, print a success message and return true.
    • If not, print "Server unavailable, retrying...".
  3. If the loop finishes without success, return false.
  4. In the main method, call tryConnect(...) with a test value and print "Failed to connect to the server after 5 attempts." if the result is false.

Lösning

java

solution

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4
Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Vi beklagar att något gick fel. Vad hände?
some-alt