Looks like double type variables have no methods.

2019-07-25 06:13发布

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!
I have JDK 1.6 and NetBeans 6.9.1. What's the problem here?

6条回答
走好不送
2楼-- · 2019-07-25 06:29

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.

查看更多
\"骚年 ilove
3楼-- · 2019-07-25 06:29

You want (java.lang.)Double not the primitive double

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-07-25 06:30

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;
查看更多
Anthone
5楼-- · 2019-07-25 06:31

Every object has a toString method, so maybe your JDK is not configured properly in NetBeans.

查看更多
Summer. ? 凉城
6楼-- · 2019-07-25 06:37

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);
查看更多
Melony?
7楼-- · 2019-07-25 06:38

Native types (int, float, double, etc) do not have methods.

查看更多
登录 后发表回答