Retry a Failing Operation
Problem
An operation fails the first a times it is called and then works. You may call it at most b times. Print success after N attempts if it works (N is the number of calls), or failed after b attempts if all b calls fail. Use exception handling inside a loop.
Constraints
- 0 <= a <= 10^4
- 1 <= b <= 10^4
Examples
Input
2 3
Output
success after 3 attempts
Input
3 3
Output
failed after 3 attempts
Solutions
A retry loop puts try-catch inside the loop. Success returns at once; a failure falls through to the next attempt. Real code also waits between attempts and limits the attempts, as here.
/*
* Problem : Retry.
* Input : Two integers: failures and maximum attempts.
* Output : The result text.
* Approach: Loop with try-catch.
* Time : O(b)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: This helper simulates the operation. It throws an exception while "failuresLeft" is above 0.
static void operation(long call, long failures) {
if (call <= failures) {
throw new IllegalStateException("temporary failure");
}
}
// This method solves the task. It receives the input and returns the answer.
static String solve(long a, long b) {
// Step 2: Try the operation again and again, but not more than b times.
for (long attempt = 1; attempt <= b; attempt++) {
try {
operation(attempt, a);
// Step 3: No exception means success. Stop at once.
return "success after " + attempt + " attempts";
} catch (IllegalStateException error) {
// Step 4: The call failed. The loop tries again.
}
}
return "failed after " + b + " attempts";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(solve(a, b));
}
}
Hints (1)
- Where do the try and catch go: inside or outside the loop?