英文:
Cannot resolve method 'intValue()'
问题
我正在尝试为一个私有的双精度变量创建一个获取方法。
当我写下:
public class {
private double x = 4.12;
public int get(){
double temp = new Double(this.x);
return temp.intValue();
}
}
IDE 建议移除 Double,不必要的装箱 'new Double(this.x)'
,并且它不识别 intValue() 方法。同样的情况也适用于仅写下:
return this.x.intValue();
英文:
I am trying to create a get method for a private double variable.
When I write
public class {
private double x = 4.12;
public int get(){
double temp = new Double(this.x);
return temp.intValue();
}
}
The IDE suggest to remove Double Unnecessary boxing 'new Double(this.x)'
and it does not recognize intValue() method. The same goes when just writing:
return this.x.intValue();
答案1
得分: 2
原始类型没有方法,创建新的Double
实例然后立即对其进行解包是没有意义的。
而是进行类型转换:
return (int) this.x;
英文:
Primitives don't have methods, and there's no point in creating a new instance of Double
only to immediately unwrap it again.
Cast instead:
return (int) this.x;
答案2
得分: 2
double
和 Double
是不同的。double
是一个原始数据类型,它没有附加的方法。Double
是一个带有附加方法的类。要在它们之间进行转换,使用类型转换。
public int get(){
return ((Double) x).intValue();
}
每种原始数据类型(int
、float
、char
等)都有一个包装类。它们通常具有相同的名称,但第一个字母大写。编译器通常会自动在原始数据类型和包装类之间进行转换,但有时我们需要通过显式类型转换来帮助它。
英文:
double
and Double
are different. double
is a primitive type, it has no methods attached. Double
is class with methods attached. To convert between them, use type casting.
public int get(){
return ((Double) x).intValue();
}
Every primitive type (int
, float
, char
, etc.) has a wrapper class. They usually have the same name, but with with the first letter capitalised. The compiler often automatically converts between the primitive and the wrapper, but sometimes we have to help it by explicitly type casting.
答案3
得分: 0
你似乎正在将 temp 存储在原始的 double 类型中,但你需要使用该类:
Double temp = new Double(this.x);
另外,不要使用 new Double(...)
,而应使用 Double.valueOf(...)
:
Double temp = Double.valueOf(this.x);
英文:
You seem to be storing temp in a primitive double, but you need to use the class:
Double temp = new Double(this.x);
Also, don't use new Double(...)
. Use Double.valueOf(...)
:
Double temp = Double.valueOf(this.x);
答案4
得分: 0
因为你将其赋值给了基本的双精度(double)类型,所以这种情况发生。尝试这样做 -
Double temp = new Double(this.x);
return temp.intValue();
英文:
It's happening because you're assigning it to primitive double type.
Try this -
Double temp = new Double(this.x);
return temp.intValue();
答案5
得分: 0
你的变量temp
被声明为double
而不是Double
,而new Double(this.x)
会创建一个Double
对象,然后将其拆箱为double
。这就是编译器报告“不必要的装箱...”的原因。
你可以简单地使用return new Double(this.x).intValue();
代替。
英文:
Your variable temp
is declared double
not Double
and new Double(this.x)
creates a Double
and unboxes it to a double
. That is why the compiler complains about Unnecessary boxing...
.
You could simply use return new Double(this.x).intValue();
instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论