2012-04-10 118 views
1

下面的代碼出現在我嘗試創建的包的主類中。它引用一個名爲Journey的助手類中的對象和方法。在由星號標記的行中調用journeyCost方法時,我得到一個「非靜態方法不能從靜態上下文中引用」的錯誤。這讓我感到困惑,因爲我的印象是,在第二行創建的Journey對象「thisJourney」構成了類的一個實例,因此意味着上下文不是靜態的。謝謝,Seany。非靜態方法不能從靜態上下文中引用

public boolean journey(int date, int time, int busNumber, int journeyType){ 
     Journey thisJourney = new Journey(date, time, busNumber, journeyType); 

     if (thisJourney.isInSequence(date, time) == false) 
     { 
      return false;    
     } 
     else 
     { 
      Journey.updateCurrentCharges(date); 

      thisJourney.costOfJourney = Journey.journeyCost(thisJourney);***** 
      Journey.dayCharge = Journey.dayCharge + thisJourney.costOfJourney; 
      Journey.weekCharge = Journey.weekCharge + thisJourney.costOfJourney; 
      Journey.monthCharge = Journey.monthCharge + thisJourney.costOfJourney; 

      Balance = Balance - thisJourney.costOfJourney; 
      jArray.add(thisJourney); 
     } 

    } 
+1

請發表(再次...)整個堆棧跟蹤:P – m0skit0 2012-04-10 13:34:56

回答

5

的錯誤意味着您正試圖調用非靜態方法以靜態方式,就像也許這一個:

Journey.journeyCost(thisJourney); 

journeyCost()聲明爲static?你的意思不是指thisJourney.journeyCost()

另外,你應該使用getter和setter方法來修改和訪問您的成員變量,所以不是:

Journey.dayCharge = ... 

你應該有

Journey.setDayCharge(Journey.getDayCharge() + thisJourney.getCostOfJourney()); 

setDayChargegetDayCharge需要在這個靜態案例)

1

也許方法journeyCost(Journey之旅)應該是靜態的?

1

您使用Journey.someMethod()的時候,someMethod是一個靜態方法。 「旅程」處於靜態環境中。 thisJourney處於非靜態環境中,因爲它是一個實例。因此,你應該使用

thisJourney.updateCurrentCharges(date); 
3

變化

Journey.journeyCost(....) 

thisJourny.journyCost(...........) 

journyCostJourny CLSS的非靜態方法,所以你必須調用此方法通過它的對象是thisJourny

使用類名稱,您只能訪問靜態成員或可以調用靜態方法該類。

3

所有這些行都需要更改。除非你真的想改變這一切的未來之旅的費用與最後三行(這將是假設那些都是靜態值)

thisJourney.costOfJourney = thisJourney.journeyCost();//dont know why you are passing the journey object to this method. 
Journey.dayCharge = Journey.dayCharge + thisJourney.costOfJourney; 
Journey.weekCharge = Journey.weekCharge + thisJourney.costOfJourney; 
Journey.monthCharge = Journey.monthCharge + thisJourney.costOfJourney; 

那些最後三行還需要工作,我不知道爲什麼你想修改靜態變量。如果你只是想設置的thisJourney

thisJourney.dayCharge = Journey.dayCharge + thisJourney.costOfJourney; 
thisJourney.weekCharge = Journey.weekCharge + thisJourney.costOfJourney; 
thisJourney.monthCharge = Journey.monthCharge + thisJourney.costOfJourney; 

收費雖然即使該電荷值應該是某個常數試試這個。你真的不應該混合同一類型的靜態類和實例類,同時交換它們的用途。

1

方法journeyCost是非靜態的;所以它是一個實例方法,它需要一個Journey的實例才能執行。句子Journey.journeyCost(thisJourney);以靜態方式調用該方法,並期望您的方法是類級方法(或靜態方法)。

所以,你可以讓你的journeyCost方法靜態你的電話的工作:

public static boolean journey(int date, int time, int busNumber, int journeyType) 

或者嘗試從一個適當的實例調用方法:

Journey aJourneyInstance = new Journey(); 
thisJourney.costOfJourney = aJourneyInstance.journeyCost(thisJourney); 
相關問題