Looks like double type variables have no methods. Something wrong with Java or NetBeans?
According to Oracle I should be able to apply methods like .intValue()
and .compareTo()
to doubles but when I write dbl.toString()
in NetBeans, for example, the IDE tells me that doubles can't be dereferenced. I can't even cast them to Integers in the form (Integer) dbl
!
The methods you're mentioning are found on the Double class (and not in the double primitive type). It's always more efficient to use primitive types, but if you absolutely need those methods, create a new Double object like this:
double d = 10.0;
Double myDouble = new Double(d);
The problem is your understanding of objects vs. primitives.
More than anything else, you just need to recognize that the capitalized names are object classes that act like primitives, which are really only necessary when you need to send data from primitives into a method that only accepts objects. Your cast failed because you were trying to cast a primitive (double) to an object (Integer) instead of another primitive (int).
Here are some examples of working with primitives vs objects:
The Double class has a static method toString():
double d = 10.0;
// wrong
System.out.println(d.toString());
// instead do this
System.out.println(Double.toString(d));
Other methods can use operators directly rather than calling a method.
double a = 10.0, b = 5.0;
// wrong
if( a.compareTo(b) > 0 ) { /* ... */ }
// instead you can simply do this:
if( a >= b) { /* ... */ }
int a = 0;
double b = 10.0;
// wrong
a = b.intValue();
// perform the cast directly.
a = (int)b;
double is a primitive not an Object. As such it has no methods. Generally what you want to do is use the language like.
double d = 1.1;
System.out.println("d= "+d); // calls Double.toString(d) for you.
int i = (int) d; // more efficient than new Double(d).intValue();
if (d >= 1.0) // does a compare.
Perhaps if you say what you are trying to achieve we can point you to the Java code which will do that.
Every object has a toString method, so maybe your JDK is not configured properly in NetBeans.
You want (java.lang.)Double
not the primitive double
Native types (int
, float
, double
, etc) do not have methods.
精彩评论