简体   繁体   English

Java方法返回double | 整型

[英]Java method returns double | int

I need a method that will accept String number as a parameter and return double if it has a remainder, or int if it is decimal. 我需要一个方法,该方法将接受String数字作为参数,如果有余数,则返回double;如果为十进制,则返回int。

I wrote such code: 我写了这样的代码:

 private double convertToNumber(String number) {
    double d = Double.parseDouble(number);
    if (d % 1.0 == 0) {
        return Integer.parseInt(number);
    } else {
        return d;
    }
}

but as signature of this method is double it returns double in any case. 但由于此方法的签名为double,因此无论如何都会返回double。

Please give me some hint. 请给我一些提示。

The signature of your function can only be of one (1) type, either int or double, but not both. 函数的签名只能是一(1)种类型,可以是int或double,但不能两者都为。 You can maybe try to redesign your function to return a boolean if the number has a fractional part (true) or (false) it doesn't. 如果数字的小数部分为(true)或(false),则可以尝试重新设计函数以返回布尔值。

Please remember that integers can't hold fractional parts, so operations like 请记住,整数不能包含小数部分,因此类似

int a = 3 / 2;

will set a to 1 not to 1.5 a设置为1而不是1.5

Why not return a Number from your method: 为什么不从您的方法返回Number

private Number convertToNumber(String number) {
    double d = Double.parseDouble(number);
    if (d % 1.0 == 0) {
        return Integer.parseInt(number);
    } else {
        return d;
    }
}

Both Integer and Double are subclasses of Number . IntegerDouble都是Number子类。

You can't have two different return types or change the method's return type in Java. 您不能有两种不同的返回类型,也不能在Java中更改方法的返回类型。 You can have different method signatures with different return types but then you're calling two separate methods which defeats the purpose of what you are trying to accomplish. 您可以使用具有不同返回类型的不同方法签名,但是随后您将调用两个单独的方法,这违背了您要实现的目标。

The best you can do in your case is create an object that you pass into the function in which you will set a flag that tells you which value to read. 在这种情况下,您可以做的最好的事情就是创建一个对象,并将其传递给函数,在该函数中您将设置一个标志,该标志告诉您要读取的值。 You will also populate either the int value or the double value. 您还将填充int值或double值。

When the method returns the boolean flag will tell the client code which value is the correct one to consume. 当该方法返回时,布尔标志将告诉客户端代码哪个值是要使用的正确值。

class MyConverter {
    public String number;
    public boolean isInt;
    public double doubleVal;
    public int intVal;
}

 private void convertToNumber(MyConverter conv) {
    double d = Double.parseDouble(conv.number);
    if (d % 1.0 == 0) {
        conv.isInt = true;
        conv.intVal = Integer.parseInt(number);
    } else {
        conv.doubleVal = d;
    }
}

I'm not quire sure I understand the intention of returning a double or and int knowing that's not really possible for a single function to return different data types. 我不确定我是否了解返回doubleint的意图,因为单个函数实际上不可能返回不同的数据类型。

What I think I understand from your sample code, is that if a String (For example, "123.0" doesn't matter how many trailing zeros) is passed into the CalculatorEngine , from the link you provided, you want it to be treated as an int and for the math operator to perform calculations with an int and a double (since currentTotal is a double ). 我想从您的示例代码中了解到的是,如果从您提供的链接中将一个字符串(例如,“ 123.0”与多少个零结尾无关)传递到CalculatorEngine ,则希望将其视为一个int ,以便数学运算符使用intdouble进行计算(因为currentTotal是double )。

Now after all the calculations are done, if currentTotal ends with a .0 then you probably want that treated as an int also and drop the point, otherwise keep the point. 现在,在完成所有计算之后,如果currentTotal以.0结尾,那么您可能希望也将其视为int并丢弃该点,否则保留该点。

If I'm understanding this correctly, here's what I think CalculatorEngine might look like: 如果我正确理解这一点,那么我认为CalculatorEngine可能看起来像这样:

public static void main(String[] args) {
    CalculatorEngine ce = new CalculatorEngine();
    ce.equal("1.01");
    ce.add("12");
    System.out.println(ce.getTotalString());
    ce.subtract("0.01");
    System.out.println(ce.getTotalString());
    ce.multiply("100.00000");
    System.out.println(ce.getTotalString());
    ce.divide("123");
    System.out.println(ce.getTotalString());
}

public static class CalculatorEngine {
    private enum Operator {
        ADD, SUBTRACT, MULTIPLY, DIVIDE
    }

    private double currentTotal;

    public CalculatorEngine() {
        currentTotal = 0;
    }

    public String getTotalString() {
        return currentTotal % 1.0 == 0 
                ? Integer.toString((int)currentTotal) 
                : String.valueOf(currentTotal);
    }

    public void equal(String number) {
        currentTotal = Double.parseDouble(number);
    }

    public void add(String number) {
        convertToDouble(number, Operator.ADD);
    }

    public void subtract(String number) {
        convertToDouble(number, Operator.SUBTRACT);
    }

    public void multiply(String number) {
        convertToDouble(number, Operator.MULTIPLY);
    }

    public void divide(String number) {
        convertToDouble(number, Operator.DIVIDE);
    }

    public void changeSign(String number) {
        Double d = Double.parseDouble(number);
        currentTotal = d * (-1);
    }

    public void dot(String number) {
        // todo
    }

    private boolean isDouble(String number) {
        double d = Double.parseDouble(number);
        return d % 1.0 != 0;
    }

    private void convertToDouble(String number, Operator operator) {
        double dblNumber = Double.parseDouble(number);
        switch (operator) {
            case ADD:
                add(dblNumber);
                break;
            case SUBTRACT:
                subtract(dblNumber);
                break;
            case MULTIPLY:
                multiply(dblNumber);
                break;
            case DIVIDE:
                divide(dblNumber);
                break;
            default:
                throw new AssertionError(operator.name());   
        }
    }

    private void add(double number) {
        currentTotal += number % 1.0 == 0 ? (int)number : number;
    }

    private void subtract(double number) {
        currentTotal -= number % 1.0 == 0 ? (int)number : number;
    }

    private void multiply(double number) {
        currentTotal *= number % 1.0 == 0 ? (int)number : number;
    }

    private void divide(double number) {
        currentTotal /= number % 1.0 == 0 ? (int)number : number;
    }
}

Results: 结果:

13.01
13
1300
10.56910569105691

Best you can do is to create a base class and two classes which extends first class. 最好的办法是创建一个基类和两个扩展第一类的类。

IntegerClass has an integer attribute and FloatClass a float atrribute. IntegerClass具有整数属性,FloatClass具有浮点属性。 Then inside the method you instsntiate IntegerClass or FloatClass depending of the String, but you returns the BaseClass. 然后在该方法内部,根据String实例化IntegerClass或FloatClass,但您将返回BaseClass。

Then using instanceOf determine which is returned. 然后使用instanceOf确定返回哪个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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