即時得到一個錯誤說「值不能得到解決」如何平方一個指定的int值?
public static MyInt square(MyInt a) {
double sqred = a.value;
MyInt sqrObjt = new MyInt(sqred);
return sqrObjt;
}
這裏是我的構造
public MyInt(int value){
this.value = value;
}
即時得到一個錯誤說「值不能得到解決」如何平方一個指定的int值?
public static MyInt square(MyInt a) {
double sqred = a.value;
MyInt sqrObjt = new MyInt(sqred);
return sqrObjt;
}
這裏是我的構造
public MyInt(int value){
this.value = value;
}
確保您已宣佈在明特類整型字段值。另外請確保在您的方形方法中將double轉換爲整數。這對我來說可以。
public class MyInt {
int value; // make sure you don't forget to declare the field
public static MyInt square(MyInt a) {
double sqred = a.value; // you could've just done int sqred = a.value * a.value rather than have a double
MyInt sqrObjt = new MyInt((int) sqred); // don't forget to cast sqred to int
return sqrObjt;
}
public MyInt(int value){
this.value = value;
}
public static void main(String[] args) {
MyInt four = new MyInt(4);
MyInt fourSquares = square(four);
System.out.println(fourSquares.value);
}
}
我想這裏的靜態方法是類別MyInt
以外的地方。你可能不想要一個公共的靜態方法,這是一個更爲程序化的方法來解決這個問題,而不是一個面向對象的方法。相反,添加非靜態方法的類MyInt
:
public MyInt square() {
return new MyInt(this.value * this.value);
}
用法:
MyInt squared = someMyInt.square();
我可以想象你的主要問題是,你永遠不會在類中的任何時候宣佈value
的事實。但是我擴大了@junvar給出的答案,包括了封裝的getter和setter。這裏是我該怎麼做......
public class MyInt {
private int value;
void setValue(int value) { //setter
this.value = value;
}
int getValue() { //getter
return this.value;
}
int square() { //square method
int sqred = getValue() * getValue();
return sqred;
}
public MyInt(int value) { //constructor
setValue(value);
}
public static void main(String[] args) { //main to run it
MyInt testCase = new MyInt(3);
System.out.println(testCase.square());
}
}
錯誤在哪裏? –
並且''MyInt.value'在你的'square'方法中可見? –
確保'value'是'public' – Arijoon