2012-04-18 112 views
0

這裏引用是錯誤消息非靜態方法...不能從靜態上下文

non static method hero(double,double,double) cannot be reference from a static context

下面是類方法。

class MyMath { 
    double hero(double n1, double n2, double n3) 
    { 
    double n4; 
    double n5; 
    n4 = (n1 + n2 + n3)/2; 
    n5 = Math.sqrt((n4 * (n4 - n1) * (n4 - n2) * (n4 - n3))); 
    return n5; 
    } 
} 

這裏是主程序

static double hero(double n1, double n2, double n3){...} 
+4

[Java - 對非靜態字段列表進行靜態引用]的可能重複(http://stackoverflow.com/questions/10200740/java-making-a-static-reference-to-the-non-靜態字段列表) – Perception 2012-04-18 06:36:04

回答

1

你的英雄方法應該放,使其static。否則,只需創建一個MyMath對象並調用該函數。

MyMath m = new MyMath(); 
area_of_triangle = m.hero(length_of_a,length_of_b,length_of_c); //No need to typecast too 
1

如果你想你的方法hero使用類名被稱爲

double length_of_a; 
double length_of_b; 
double length_of_c; 
double area_of_triangle; 

area_of_triangle = (double) MyMath.hero(length_of_a,length_of_b,length_of_c); 
0

,因爲您嘗試訪問MyMath.hero就好像它是一個static方法你得到這個錯誤。爲了解決這個問題,您必須聲明方法herostatic或首先創建一個類型爲MyMath的對象並從該對象中調用該方法。

1

您的方法hero不是靜態的。這意味着您只能在類MyMath的實例上調用它。您正在嘗試調用它,彷彿它是這裏的靜態方法:

area_of_triangle = (double) MyMath.hero(length_of_a,length_of_b,length_of_c); 

要麼使hero方法static,或創建MyMath的實例並調用它的方法。

// Solution 1: Make hero static 
class MyMath { 
    static double hero(double n1, double n2, double n3) 
     // ... 

// Solution 2: Call hero on an instance of MyMath 
MyMath m = new MyMath(); 

area_of_triangle = m.hero(length_of_a,length_of_b,length_of_c); 

注:鑄造方法double的結果是沒有必要的,該方法已經返回double

1

您的hero()方法未設置爲靜態。您可以讓hero()像一個靜態方法,以便:

static double hero(double n1, double n2, double n3) 
{ 
    ... 

,或者你可以像創建MYMATH的新實例:

MyMath newMath = new MyMath(); 

,然後調用:

newMyMath.hero(length_of_a,length_of_b,length_of_c); 
+0

謝謝Karthik。 V – Hrfpkj 2012-04-18 06:40:38

0

主要方法是靜態的,並且java不允許在靜態方法中引用非靜態obj。 所以你應該使hero()方法也是靜態的,或者從非靜態方法引用它。

相關問題