簡體   English   中英

如何實現一個將兩個任意類型的數字(雙精度,整數)相加的靜態方法?

[英]How do you implement a single static method that adds two numbers of any type (Double, Integer)?

我需要一個靜態方法,該方法只需將兩個不同的數字加在一起並返回結果。 但是,它需要能夠接受不同類型的數字,例如Integer和Doubles,這正是我遇到的問題。 這是我擁有的主要方法,無法更改。

public static void main(String[] args)
{
    Double answer1 = add(2, 7);
    Number answer2 = add(new Integer(4), new Double(5.2));
    double answer3 = add(8, 1.3);
    System.out.println(answer1 + " " + answer2 + " " + answer3);
} 

public static Double add(Double num1, Integer num2)
{
    return num1 + num2;
}

上面的方法具有正確的主體,我只是不知道在靜態之后Double應該在哪里。 是否有一些類型可以同時容納雙精度和整數?

新情況:

public static double add(Number num1, Number num2)
{
    return num1 + num2; //error is here
}

您可以使用常見的基類Number

public class Test {
    public static void main(String[] args) {
        int x = 5;
        double y = 10;
        System.out.println(getDoubleValue(x, y));
    }

    private static double getDoubleValue(Number x, Number y){
        return x.doubleValue() + y.doubleValue();
    }
}

輸出:

15.0

 public void draw(String s) {
    ...
 }
 public void draw(int i) {
    ...
 }
 public void draw(double f) {
    ...
 }
 public void draw(int i, double f) {
    ...
 }

看下面的鏈接

http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

意味着您必須使用方法重載

您應該使用方法重載。

Double Foo()  // Version with no arguments
{
}

Double Foo(int arg) // Version with a single int
{
}

Double add(Double num1, Integer num2) // Version with integer  and double parameters
{
}

您可以為此使用方法重載。 創建具有不同數據類型的相同方法:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM