简体   繁体   中英

Comparing Strings in If loop using Coupon.equals

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");  
}

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!");
    }
}

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM