Domanda

How to convert Double to Number in Java, like in the code below?

public Number parse(String text, ParsePosition status) {
    // find the best number (defined as the one with the longest parse)
    int start = status.index;
    int furthest = start;
    double bestNumber = Double.NaN;
    double tempNumber = 0.0;
    for (int i = 0; i < choiceFormats.length; ++i) {
        String tempString = choiceFormats[i];
        if (Misc.regionMatches(start, tempString, 0, tempString.length(), text)) {
            status.index = start + tempString.length();
            tempNumber = choiceLimits[i];
            if (status.index > furthest) {
                furthest = status.index;
                bestNumber = tempNumber;
                if (furthest == text.length()) break;
            }
        }
    }
    status.index = furthest;
    if (status.index == start) {
        status.errorIndex = furthest;
    }
    int c= 0;
    return new Double(bestNumber); 
}

But in Eclipse it shows

Type mismatch: cannot convert from Double to Number

Actually this code belongs to ChoiceFormat.java class from java.text package.

È stato utile?

Soluzione

java.lang.Double is a subclass of java.lang.Number. Hence the posted code shouldn't show any compilation error if you are returning a java.lang.Double from a method which returns java.lang.Number .

As Jon Skeet pointed out, "you've got a different Double type or a different Number type somewhere". Please double check to see if you are using java.lang.Double and java.lang.Number.

Altri suggerimenti

Use casting

Double d=new Double(2);
Number n=(Number)d;

in your case

Double d=new Double(bestNumber);
Number n=(Number)d;

return n;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top