Created
July 19, 2022 10:37
-
-
Save Minecraftian14/5ccad071c77daee2dd82cdadda1951da to your computer and use it in GitHub Desktop.
Mini Java Projects: Currency Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https=//hackr.io/blog/java-projects Currency Converter | |
import java.net.URL; | |
import java.util.*; | |
import java.util.stream.Collectors; | |
public class CurrencyConverter { | |
public static void main(String[] args) throws Exception { | |
if (args == null || args.length == 0 || args[0].equals("--help") || args[0].equals("-h")) { | |
System.out.println(""" | |
CLI Tags: | |
--help, -h Display this message. | |
--list-conversions, -l Display a list of supported conversions. | |
CLI Arguments: | |
0: currency_to:str The 3 character currency code, to which the amount is to be converted. | |
1: currency_from=INR:str The 3 character currency code, from which the amount is to be converted. | |
2: base_value=1.0:double The amount to be converted. | |
"""); | |
return; | |
} | |
var result = new String(new URL("https://cdn.moneyconvert.net/api/latest.json").openConnection().getInputStream().readAllBytes()); | |
result = result.substring(30, result.length() - 52); | |
Map<String, Double> map = Arrays.stream(result.split(", ")).map(s -> s.split(": ")) | |
.collect(Collectors.toMap(ss -> ss[0].replace("\"", ""), ss -> Double.parseDouble(ss[1]))); | |
if (args[0].equals("--list-conversions") || args[0].equals("-l")) { | |
map.keySet().stream().sorted().forEach(System.out::println); | |
return; | |
} | |
String currency_to = args[0]; | |
if (!map.containsKey(currency_to)) | |
System.out.println("There is no such currency code as " + currency_to + " in the database."); | |
String currency_from = args.length >= 2 ? args[1] : "INR"; | |
if (!map.containsKey(currency_from)) | |
System.out.println("There is no such currency code as " + currency_from + " in the database."); | |
double base = args.length >= 3 ? Double.parseDouble(args[2]) : 1.0; | |
System.out.println(base * map.get(currency_to) / map.get(currency_from)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment