gpt4 book ai didi

java - 创建一个 Util 类

转载 作者:搜寻专家 更新时间:2023-11-01 03:43:32 24 4
gpt4 key购买 nike

我创建了一个货币格式器类。我希望这是一个 util 类,可以被其他应用程序使用。现在我只使用一个字符串,而不是希望它由导入我的 currencyUtil.jar

的应用程序设置
public class CurrencyUtil{
public BigDecimal currencyUtil(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
BigDecimal amount = new BigDecimal("123456789.99"); //Instead I want the amount to be set by the application.
ThemeDisplay themeDisplay =
(ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
Locale locale = themeDisplay.getLocale();

NumberFormat canadaFrench = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
NumberFormat canadaEnglish = NumberFormat.getCurrencyInstance(Locale.CANADA);
BigDecimal amount = new BigDecimal("123456789.99");
DecimalFormatSymbols symbols = ((DecimalFormat) canadaFrench).getDecimalFormatSymbols();
symbols.setGroupingSeparator('.');
((DecimalFormat) canadaFrench).setDecimalFormatSymbols(symbols);

System.out.println(canadaFrench.format(amount));
System.out.println(canadaEnglish.format(amount));
//Need to have a return type which would return the formats
return amount;
}
}

让调用这个util类的其他应用程序成为

 import com.mypackage.CurrencyUtil;
...
public int handleCurrency(RenderRequest request, RenderResponse response) {
String billAmount = "123456.99";
CurrencyUtil CU = new currencyUtil();
//Need to call that util class and set this billAmount to BigDecimal amount in util class.
//Then it should return both the formats or the format I call in the application.
System.out.println(canadaEnglish.format(billAmount); //something like this
}

我做了什么改变?

最佳答案

您需要创建一个 CurrencyUtil 类的对象。

CurrencyUtil CU = new CurrencyUtil();
//To call a method,
BigDecimal value=CU.currencyUtil(request,response);

我建议 currenyUtil 方法应该是 static 并且它需要三个参数。

public class CurrencyUtil
{
public static BigDecimal currencyUtil(
RenderRequest renderRequest,
RenderResponse renderResponse,
String amountStr) throws IOException, PortletException
{
BigDecimal amount = new BigDecimal(amountStr);
...
}
}

你可以这样调用它,

 BigDecimal value=CurrencyUtil.currencyUtil(request,response,billAmount);

关于java - 创建一个 Util 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8699359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com