2016-07-08 118 views
-3

我有這段代碼最後的目標是排序多個數組。 當我嘗試訪問我的顏色比較器上的「.color」時出現問題。 對不起,這個愚蠢的問題,但我是新的Android。構造函數的問題

我的構造函數:

import java.util.*; 
    public class ColorClothes { 

     public ColorClothes() // <------ method 
     { 

     } 

     public Clothes[] Initialize(Clothes[] item) { 
      Clothes firstry[] = new Clothes[4]; 


      System.out.println("Unsorted"); 

      for (int i = 0; i < item.length; i++) { 
       System.out.println(item[i].record + "  " + item[i].color + "  " + item[i].clothes); 
      } 

      System.out.println("\nSorted By Color\n"); 

      Arrays.sort(item, new ColorComparator()); 

      for (int i = 0; i < item.length; i++) { 
       System.out.println(item[i].record + "  " + item[i].color + "  " + item[i].clothes); 
      } 





      return item; 

     } 


     public class Clothes { 
      public int record; 
      public String color; 
      public String clothes; 
     } 
    } 

我ColorComparator:

import java.util.Comparator; 

class ColorComparator implements Comparator 
{ 
    public int compare(Object str1, Object str2) 
    { 
     String str1Color = ((ColorClothes)str1).color; 
     String str2Color = ((ColorClothes)str2).color; 

     return str1Color.compareTo(str2Color); 

    } 
} 

無法解析 「色」 這發生在我的ColorComparator。我做錯了什麼?

+0

'ColorClothes'沒有'color'字段,而是'Clothes'類。 –

+2

「ColorClothes」的一個實例沒有顏色。這聽起來像你應該接受一個'Clothes'的實例來代替。我強烈建議,如果你是Java新手,你可以避免使用嵌套類型,因爲它們會讓你感到困惑。我還建議你瞭解泛型,以便你可以實現'Comparator '並避免公共領域。 –

+0

問題解決ty幫助我瞭解我的錯誤:) –

回答

0

你的顏色屬性是在類Clothes但你鑄造成ColorClothes((ColorClothes)str1).color

嘗試:

((Clothes)str1).color 

PS:類公共屬性是不是真正的面向對象編程

0

布沒有得到解決。 試試這個:

String str1Color = ((ColorClothes.Clothes)str1).color; 

String str2Color = ((ColorClothes.Clothes)str2).color; 
+0

請編輯更多信息。僅限代碼和「嘗試這個」的答案是不鼓勵的,因爲它們不包含可搜索的內容,也不解釋爲什麼有人應該「嘗試這個」。 – abarisone