![](/img/trans.png)
[英]non-static method toString() cannot be referenced from a static context
[英]non-Static method toString cannot be referenced from a static context
我正在嘗試創建一個程序來讀取用戶輸入並存儲它,然后計算多邊形的面積。 當我嘗試編譯它時,它給了我一個錯誤,即.toString
是非靜態的。
import java.util.Scanner;
class regularpoTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean finished = false;
double s;
double n;
double area;
//starts loop to record data
do {
s =0;
n =0;
System.out.println("Enter the side length, or anything else to quit: ");
s = in.nextDouble();
in.nextLine();
if (in.hasNextDouble()) {
System.out.println("Enter number of sides");
n = in.nextDouble();
area = (s*s*n)/(4*Math.tan(Math.PI/n));
} else {
finished = true;
}
} while(!finished);
//This prints out the student details
System.out.println(regularpo.toString());
}
}
public class regularpo {
private double side;
private double numberOf;
private double area;
public regularpo(double side, double numberOf){
side = 0;
numberOf = 0;
area = 0;
}
public double getSide(){
return side;
}
public double getNumberOf(){
return numberOf;
}
public String toString(){
return ("area = " + area+ " side length "+side+ " number of sides "+numberOf);
}
}
您正在嘗試調用類的方法,當該方法已被定義為(並且僅作為)該類的實例的方法時。 也許您的意思是創建該類的對象,並調用其toString
方法,盡管我無法從您的代碼中確定。
建議:
1)消除“regularpoTest”。 只需將“main()”移動到“regularpo”即可。
2) 將“RegularPo”大寫(按照慣例,類名應以大寫字母開頭)。
3)使RegularPo構造函數實際保存初始值(不僅僅是將它們設置為零)。
……而且,最重要的是……
4)你的主要應該調用RegularPo regularPo = new RegularPo (...)
。 然后引用對象實例“regularPo”。
嘗試創建一個類regularpo
的對象並在該對象上調用toString
regularpo obj=new regularpo();
obj.toString();
同樣按照慣例,類名必須以大寫開頭,因此將您的類命名為Regularpo
toString() 是regularpro類中的一個非靜態方法,我們知道非靜態屬於一個對象,所以我們需要創建同一個類的對象並調用它。
toString() 屬於 Object 類,因此它的非靜態方法。
正規寶 obj=新正規寶(); obj.toString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.