2015-12-04 15 views
-3

//這是方法的名稱。該方法旨在從存儲在程序外部的文本文件中讀取信息。該方法包含在名爲FileHelper的類中。這個類包含了其他各種方法來幫助完成基於程序之外的文件的讀寫任務。如何爲Java中另一個類中的方法調用外部方法?試圖調用的方法是使用哈希映射的方法

public HashMap<String, String> readAMap (String filename) { 

    HashMap<String, String> map = new HashMap<>(); 
    try (BufferedReader reader = 
      new BufferedReader(new FileReader(filename))) { 
     String word; 
     word = reader.readLine(); 
     while(word != null) { 
      String response = reader.readLine(); 
      if(response != null) { 
       response = response.trim(); 
       if(response.length() != 0) { 
        map.put(word, response); 
       } 
       else { 
        System.out.println("Blank response for " + 
             word + " in file " + 
             filename); 
       } 
      } 
      else { 
       System.out.println("Missing response for " + 
            word + " in file " + 
            filename); 
      } 
      word = reader.readLine(); 
     } 
    } 
    catch(IOException e) { 
     System.out.println("Problem reading file: " + filename + 
          " in readAMap"); 
    } 
    return map; 
} 

//這是我用來調用上述方法的方法,這個方法是另一個類。

private void fileResponseMap() 
{ 
    FileResponseMap = FileHelper.HashMap<String, String>readAMap(JavaFile); 
    return FileResponseMap; 
} 
} 

//我試圖與r

+3

請多關注一下您提出的問題。解釋代碼,解釋你的問題,請給我們一點幫助。 –

回答

1
  • 實例化的類提供了readMap方法。
  • 調用實例方法

class Foo { 
    public HashMap<String, String> readAMap(String filename) { 
     // ... 
    } 
} 

private HashMap<String, String> fileResponseMap() { 
    Foo foo = new Foo(); 

    String javaFile = "my-java-file.txt"; 
    HashMap<String, String> map = foo.readAMap(javaFile); 

    return map; 
} 
0

如果你想打電話給你的方法從這裏應該這樣做: 所有東西實例之前你的類ex:他的名字是FileResponseMap這樣的:

FileResponseMap ycn = new FileResponseMap(); 

並調用你的方法是這樣的:

`ycn.readAMap ("JavaFile");`. 

而且您有方法與返回HashMap<String, String>

private HashMap<String, String> fileResponseMap() 
    { 
     FileResponseMap ycn = new FileResponseMap(); 
     HashMap<String, String> hmfile = ycn.readAMap("JavaFile"); 

    return hmfile ; 
    } 
} 
2

你的方法readAMap也不是一成不變的,因此它不能在你嘗試在fileResponseMap的方式的方式進行訪問。

要麼你可以聲明爲靜態:

public static HashMap<String, String> readAMap (String filename) { 
... 

或者在調用方法創建的FileHelper一個實例,並調用該實例的方法:

private HashMap<String, String> fileResponseMap() 
{ 
    FileHelper fileHelper = new FileHelper(); 
    return fileHelper.readAMap(JavaFile); 

} 

還必須定義你的回報在返回HashMap時鍵入。

相關問題