-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrencyConverter.java
More file actions
54 lines (43 loc) · 1.97 KB
/
CurrencyConverter.java
File metadata and controls
54 lines (43 loc) · 1.97 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
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;
public class CurrencyConverter {
private static final String API_URL = "https://api.exchangerate-api.com/v4/latest/";
public static double getExchangeRate(String baseCurrency, String targetCurrency) throws IOException {
URL url = new URL(API_URL + baseCurrency);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("HTTP Response Code: " + responseCode);
}
Scanner scanner = new Scanner(url.openStream());
StringBuilder jsonResponse = new StringBuilder();
while (scanner.hasNext()) {
jsonResponse.append(scanner.nextLine());
}
scanner.close();
JSONObject data = new JSONObject(jsonResponse.toString());
return data.getJSONObject("rates").getDouble(targetCurrency);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter base currency (e.g., USD): ");
String baseCurrency = scanner.next().toUpperCase();
System.out.print("Enter target currency (e.g., EUR): ");
String targetCurrency = scanner.next().toUpperCase();
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
try {
double rate = getExchangeRate(baseCurrency, targetCurrency);
double convertedAmount = amount * rate;
System.out.println("Converted Amount: " + convertedAmount + " " + targetCurrency);
} catch (IOException e) {
System.out.println("Error retrieving exchange rate: " + e.getMessage());
}
scanner.close();
}
}