java conditional operator and different types

前端 未结 3 2155
死守一世寂寞
死守一世寂寞 2020-12-20 23:34

I have two methods in the Item Class:

public void setValue(String v);
public void setValue(Double v);

and I want to use Cond

3条回答
  •  抹茶落季
    2020-12-21 00:13

    IF you want to go with the ternary operator only following code will solve your problem. For testing I have put false as the default value you can put your conditional expression.

    public class st1 {
        public static void main (String []args) {
            Item i = new Item();
            i.setValue (false?"test":0.0);
        }
    }
    
    class Item {
        private String str;
        private double d;
        public void setValue (Object str) {
            try {
                d = Double.parseDouble (str.toString());
                System.out.printf ("Double type : %f", d);
            } catch (NumberFormatException ne) {
                this.str = str.toString();
                System.out.printf ("String type : %s", this.str);
            }
        }
    }
    

提交回复
热议问题