-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrencyApp.java
More file actions
107 lines (90 loc) · 3.94 KB
/
CurrencyApp.java
File metadata and controls
107 lines (90 loc) · 3.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
/**
* CUSTOM EXCEPTION: Specifically for API or Network failures.
*/
class ApiException extends Exception {
public ApiException(String message) { super(message); }
}
/**
* SERVICE LAYER: CurrencyService
* Responsibility: Fetching data from the Frankfurter API (European Central Bank data).
*/
class CurrencyService {
// Standard User-Agent header to identify our traffic (Professional Standard)
private static final String USER_AGENT = "JavaCurrencyConverter/1.0 (Student Project)";
private static final String BASE_URL = "https://api.frankfurter.app/latest?from=USD&to=";
/**
* Fetches rate dynamically for a specific target currency.
* @param targetCurrency The 3-letter code (e.g., EUR, JPY)
* @return The exchange rate
*/
public double getRate(String targetCurrency) throws Exception {
String url = BASE_URL + targetCurrency;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("User-Agent", USER_AGENT) // Identify our app
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new ApiException("API Error: Received status code " + response.statusCode());
}
return parseRate(response.body(), targetCurrency);
}
/**
* Helper Method: Parses the JSON string manually.
*/
private double parseRate(String responseBody, String currency) {
String searchKey = "\"" + currency + "\":";
int startIndex = responseBody.indexOf(searchKey) + searchKey.length();
int endIndex = responseBody.indexOf("}", startIndex);
return Double.parseDouble(responseBody.substring(startIndex, endIndex));
}
}
/**
* MAIN EXECUTION: The Command Line Interface
*/
public class CurrencyApp {
public static void main(String[] args) {
// --- DATA SETUP ---
// Major Currencies
Set<String> majors = new HashSet<>(Arrays.asList("EUR", "GBP", "JPY", "CAD", "AUD"));
// Minor/Emerging Currencies (Supported by Frankfurter API)
Set<String> minors = new HashSet<>(Arrays.asList("INR", "BRL", "ZAR", "TRY", "THB"));
Scanner scanner = new Scanner(System.in);
CurrencyService service = new CurrencyService();
System.out.println("=== PROFESSIONAL MULTI-CURRENCY CONVERTER ===");
System.out.println("Available Majors: " + majors);
System.out.println("Available Minors: " + minors);
try {
System.out.print("\nEnter Target Currency Code: ");
String target = scanner.next().toUpperCase();
// Validation logic
if (!majors.contains(target) && !minors.contains(target)) {
System.out.println("Error: Currency not supported.");
return;
}
System.out.print("Enter Amount in USD: ");
double amount = scanner.nextDouble();
System.out.println("Fetching live rate for " + target + "...");
double rate = service.getRate(target);
// Output Results
System.out.println("\n" + "=".repeat(20));
System.out.printf("Result: %.2f USD = %.2f %s\n", amount, (amount * rate), target);
System.out.printf("Exchange Rate: 1 USD = %.4f %s\n", rate, target);
System.out.println("=".repeat(20));
} catch (InputMismatchException e) {
System.err.println("Input Error: Please enter numbers only.");
} catch (Exception e) {
System.err.println("System Error: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Application Closed.");
}
}
}