英文:
Comparing Strings in If loop using Coupon.equals
问题
我正在从JSON中读取数据,并尝试与我想要的验证进行比较。
它能够运行,但是否有更好的方法呢?
我希望它能够验证从“0.025”、“0.03”、“0.035”、“0.04”、“0.045”、“0.05”等直到1.00的值。
代码:
String Coupon = (String) data.get("coupon");
if (Arrays.asList("0.025", "0.03", "0.035", "0.04", "0.045", "0.05").contains(Coupon)) {
System.out.println("找到有效数据");
}
英文:
I am reading data from a JSON and am attempting to compare to the validations I want to have.
It works, but is there a better way to do it?
I want it do validate values from "0.025", "0.03", "0.035", "0.04", "0.045", "0.05", etc.. until 1.00
code:
String Coupon = (String) data.get("coupon");
if(Coupon.equals("0.025")||Coupon.equals("0.03")||(Coupon.equals("0.035")||Coupon.equals("0.04"))||(Coupon.equals("0.045")||Coupon.equals("0.05"))){
System.out.println("Valid Data Found");
}
答案1
得分: 2
使用一个Set
来校验针对一组固定数据的最简单方法可能是检查你的优惠券是否包含在有效数据中。
例如:
public static void main(String[] args) {
String inputString = "0.03";
Set<String> validCoupons = new HashSet<>(
Arrays.asList("0.025", "0.03", "0.035", "0.04", "0.045", "0.05"));
if (validCoupons.contains(inputString)) {
System.out.println("发现有效优惠券!");
}
}
英文:
Easiest way for you to verify against a fixed set of data is probably to use a Set
and check if your coupon is contained within the valid data.
For example:
public static void main(String[] args) {
String inputString = "0.03";
Set<String> validCoupons = new HashSet<>(
Arrays.asList("0.025", "0.03", "0.035", "0.04", "0.045", "0.05"));
if (validCoupons.contains(inputString)) {
System.out.println("Valid coupon found!");
}
}
答案2
得分: 0
你可以这样做:
for (double i = 0.025; i <= 1;) {
String temp = String.valueOf(i);
if (Coupon.equals(temp)) {
System.out.println("找到有效数据");
}
System.out.println(String.valueOf(temp));
BigDecimal num1 = new BigDecimal(temp);
BigDecimal num2 = new BigDecimal("0.005");
BigDecimal addResult = num1.add(num2);
String addStr = String.valueOf(addResult);
i = Double.parseDouble(addStr);
}
英文:
You can do like this:
for (double i = 0.025; i <= 1;) {
String temp=String.valueOf(i);
if (Coupon.equals(temp)) {
System.out.println("Valid Data Found");
}
System.out.println(String.valueOf(temp));
BigDecimal num1 = new BigDecimal(temp);
BigDecimal num2 = new BigDecimal("0.005");
BigDecimal addResult = num1.add(num2);
String addStr=String.valueOf(addResult);
i=Double.parseDouble(addStr);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论