I want to create a method that will change values like in cantor. I have String :
String rates = "{\"rates\":{\"CAD\":1.5563,\"HKD\":9.1212,\"ISK\":162.6,\"PHP\":57.324,\"DKK\":7.4441,\"HUF\":350.68,\"CZK\":26.083,\"AUD\":1.6442,"
"\"RON\":4.8405,\"SEK\":10.363,\"IDR\":17383.99,\"INR\":88.198,\"BRL\":6.5908,\"RUB\":87.735,\"HRK\":7.5243,\"JPY\":124.53,\"THB\":37.161,"
"\"CHF\":1.0744,\"SGD\":1.6131,\"PLN\":4.3979,\"BGN\":1.9558,\"TRY\":8.5925,\"CNY\":8.1483,\"NOK\":10.5913,\"NZD\":1.8045,\"ZAR\":20.2977,"
"\"USD\":1.1769,\"MXN\":26.066,\"ILS\":4.0029,\"GBP\":0.89755,\"KRW\":1403.15,\"MYR\":4.9194},\"base\":\"EUR\",\"date\":\"2020-08-21\"}";
I want to create method :
public double change(int value, String country) {
so if I use method like: change(100, "PLN") it should give me : 439.79
I tried to think about using Pattern, but I dont know how to put my parameter String in regex.
I tried something like this :
Pattern pattern = Pattern.compile("(?<country>\"([A-Z]){3}\"):(?<rate>[0-9] \\.[0-9] )");
CodePudding user response:
I write a method :
public static double zamien(int ilosc, String waluta, String kursy) {
double result = 0.0;
Pattern pattern = Pattern.compile("(?<kraj>([A-Z]){3}\"):(?<kurs>[0-9] \\.[0-9] )");
if(!kursy.contains(waluta)) {
throw new IllegalArgumentException("Nie ma takiej waluty!");
}
int firstIndex = kursy.indexOf(waluta);
String krajIkurs = kursy.substring(firstIndex, firstIndex 11);
//System.out.println(krajIkurs);
Matcher matcher = pattern.matcher(krajIkurs);
if (matcher.matches()) {
double rate = Double.parseDouble(matcher.group("kurs"));
result = ilosc * rate;
} else {
throw new IllegalArgumentException("zly pattern!");
}
return result;
}
It works good for me but Can I do it better?
CodePudding user response:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CurrencyConverter {
private static String rates = "{\"rates\":{\"CAD\":1.5563,\"HKD\":9.1212,\"MYR\":4.9194},\"base\":\"EUR\",\"date\":\"2020-08-21\"}";
private static JsonNode root;
static {
try {
root = new ObjectMapper().readTree(rates);
} catch (Exception e) {
throw new RuntimeException("Error while parsing rates JSON string", e);
}
}
public static double change(int value, String country) throws Exception {
JsonNode ratesNode = root.path("rates");
if (!ratesNode.has(country)) {
throw new Exception("Country not found in rates");
}
double rate = ratesNode.get(country).asDouble();
return value * rate;
}
}