2012-12-11 35 views
0

這是我的完整代碼。我的挑戰在最後3行!我無法將參數(int r)發送到findColor(int r)。任何幫助,高度讚賞。謝謝從Main方法傳遞參數

import java.util.*; 
public class NewClass { 
private HashMap <Character,HashSet> colorMap ; 

public NewClass() { 
    colorMap = new HashMap<Character, HashSet>(); 
} 

public void addColor(){ 
    HashSet a1 = new HashSet(); 
    a1.add("Yellow"); 
    a1.add("Blue"); 
    a1.add("Pink"); 
    colorMap.put('X', a1); 
    HashSet a2 = new HashSet(); 
    a2.add("White"); 
    a2.add("Brown"); 
    a2.add("Blue"); 
    a2.add("Black"); 
    colorMap.put('W', a2); 
}  

public Set<String> findColor(int r) 
{ 
Set<String> colors = new HashSet<String>(); 
    { 
    for(Character m : colorMap.keySet()) 

    if(r < colorMap.size()) 
     { 
     Set<String> zone = colorMap.get(m); 
     System.out.println("Zone " + zone + " has more than " + r + " colors"); 
     }   
    } 
    return colors; 
}  

public static void main(String [] args){ 

    Set<String> colors; 
    NewClass a = new NewClass(); 
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter a numbers \n"); 
    int r = input.nextInt(); 
    colors = findColor(r); 
    a.findColor(r);  
}  
} 

任何幫助,高度讚賞。謝謝!

+3

爲什麼你不能?你是否收到錯誤信息?它不會編譯?您需要更具體地瞭解實際問題,或者您的問題可能會被降低和關閉。 –

回答

1

一個問題,我可以講的是:

int r = input.nextInt(); 
    //colors = findColor(r); 
    Set<String> colors = a.findColor(r);  

刪除第二行

findColor(int r)不是一個靜態方法,所以您不能直接靜態方法裏面打電話,你需要使用實例參考(這是上面代碼中的line3)。

+0

謝謝!注意到。但仍不能按預期工作! – StillTrying

+0

最後的顏色內容是什麼? – Adude11

+0

輸出是[] – StillTrying

0

看你的最後3行:

int r = input.nextInt(); 
colors = findColor(r); 
a.findColor(r); 

第2行,你想叫findColor從一個靜態方法,但findColor也不是一成不變的。這是不允許的;必須通過非靜態方法所屬的特定類的實例調用非靜態方法。

實際上在main函數的範圍內確實有NewClass的實例,您可以稱其爲a。因此,只需撥打findColor即可:

int r = input.nextInt(); 
colors = a.findColor(r); 
+0

謝謝!注意到。但是,它不能按預期工作! – StillTrying