簡體   English   中英

不能從靜態上下文引用非靜態方法

[英]Non-static method cannot be referenced from a static context

您好,我目前遇到“ Domino.java:32:錯誤:無法從靜態上下文引用非靜態方法getValue()”的常見錯誤。我有點理解這是一個問題,因為它只是該實例的一個實例。 getValue方法。 在這個compareTo方法中,我試圖傳遞一些多米諾骨牌並將其與設置的多米諾骨牌進行比較,並根據一些比較返回-1,0,1。 我需要多米諾骨牌兩邊的總和來比較它們,這就是為什么我嘗試獲取domino.getValue()的原因,在這一點上,我只是不確定如何實現此目的。 任何建議或幫助將不勝感激

public class Domino {
    public static int side1;
    public static int side2;

       public Domino(int aside, int bside){
           side1 = aside;
           side2 = bside ;
       }
       public Domino() {
           side1 = 4;
           side2 = 5;
       }

       public boolean isDouble(){
           if(side1 == side2) {
               return true;
           }
           else {
               return false;
           }
       }
       public int getValue(){
          return side1 + side2;
       }
       public int compareTo(Domino someDomino)
         {
            int count = 0;
            if(Domino.getValue() < someDomino.getValue()){
               count = -1; 
             }if(Domino.getValue() > someDomino.getValue()){
                   count = 1; 
                 }
             if(Domino.getValue() == someDomino.getValue()){
                   count = -0; 
                 }
           return count;  
         }

       public static void main(String args[]) {

       }

}

這是因為您是在compareTo方法旁邊在Domino類上靜態調用方法的。 擺脫Domino. 調用getValue()的一部分。

public int compareTo(Domino someDomino)
         {
            int count = 0;
            if(getValue() < someDomino.getValue()){
               count = -1; 
             }if(getValue() > someDomino.getValue()){
                   count = 1; 
                 }
             if(getValue() == someDomino.getValue()){
                   count = -0; 
                 }
           return count;  
         }

Domino是類本身,則需要比較的參數與當前實例的對象( 顯式參數 )( 隱含參數 )上,您正在調用方法之一,它是this

public int compareTo(Domino someDomino){
    int count = 0;
    if(this.getValue() < someDomino.getValue()){
        count = -1; 
    }else if(this.getValue() > someDomino.getValue()){
        count = 1; 
    }
    return count;  
}

這是一樣的:

public int compareTo(Domino someDomino) {
    return Integer.compare(this.getValue(), someDomino.getValue());
}

另外:

  • else if您的測試不能同時為真, else if使用else if
  • 不需要最后檢查是否equality ,如果不是<和not >那么它是==並且count將已經equals 0
  • 重要 public static int side1; => public int side1; 如果它們是靜態的,則對於每個 Domino都是相同的

最好添加Comparable接口,以允許對ex列表中的Domino進行排序,方法compareTo()將自動使用

public class Domino implements Comparable<Domino>{...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM