2016-07-09 3 views
-2

내가 같이 wordlist.txt에서 미리 정의 된 단어를 읽을 수있는 자바를 배울 수있는 사전을 만들려고하고의 값을 채우기에도 불구하고, NULL을 반환공공 정적 HashMap의 인스턴스 내가 생성자

subterfuge:something intended to misrepresent the true nature of an activity 
stymie:thwarting and distressing situation; 

하지만 으로 선언 된 ReadToHashmap 클래스의지도 인스턴스에 액세스하려고하면 액세스 할 수 있지만 항상 null을 반환합니다.

HashMap이 모두 wordlist.txt에 따라 업데이트 된지도 인스턴스에 어떻게 액세스 할 수 있습니까?

public class ReadToHashmap { 
    public static Map<String, String> map = new HashMap<String, String>(); 

    public ReadToHashmap() { 
     // TODO Auto-generated constructor stub 
    } 

    public static Map getHasMap() 
    { 
     return map; 
    } 

    public static void main(String[] args) throws Exception { 


     try{ 
      BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Maxs\\workspace\\Dictionary\\src\\wordlist.txt")); 
      String line = ""; 
      while ((line = in.readLine()) != null) { 
       String parts[] = line.split(":"); 
       map.put(parts[0], parts[1]); 
      }  
      in.close(); 
     } 
     catch(Exception e) 
     { 
      System.out.println("Erro " +e.getMessage()); 
     }  



     Iterator it = map.entrySet().iterator(); 
     while (it.hasNext()) { 
      Map.Entry pair = (Map.Entry)it.next(); 
      System.out.println(pair.getKey() + " = " + pair.getValue()); 
      it.remove(); // avoids a ConcurrentModificationException 
     } 

     findMeaning word = new findMeaning(); 
     String inputWord; 
     String outputWord; 
     System.out.println("Enter rge word to be searched "); 
     inputWord = word.getTheWord(); 
     outputWord =word.getFromDictionary(inputWord); 
     System.out.println("Thge meaning is " +outputWord); 
    } 
} 

또 다른 클래스

public class findMeaning { 
    public String inputWord; 
    public String description; 
    findMeaning() 
    { 
     inputWord = ""; 
    } 
    public String getTheWord() 
    { 

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

     try{ 
      inputWord = br.readLine(); 

     } 
     catch(IOException e) 
     { 
      System.out.println("Error while reading " +e.getMessage());  
      return ""; 
     } 
     return this.inputWord; 
    } 

    public String getFromDictionary(String key){ 

     System.out.println("The output " +ReadToHashmap.getHasMap().toString());  
     if(inputWord.isEmpty()) 
     { 
      return "No lattest input from user "; 

     } 
     description = (String) ReadToHashmap.getHasMap().get(inputWord); 
     if(description == null) 
     { 
      return "Word Doesnot exsist"; 
     } 
     return description; 

    } 

} 

답변

3

귀하의 주요 방법지도, 모든 항목을 통해 다음 반복을 채우고 그들 각각을 제거합니다. 그래서이 루프가 끝나면 맵은 비어 있습니다.

+0

감사합니다. it.remove()를 제거한 후에도 문제가 없습니다. 그건 내 편이 멍청한 실수 였어. –

+0

확실하지 않은 이유는 무엇입니까? –

1

다른 클래스에서 사용하기 전에 HashMap 내의 모든 항목을 제거하는 것처럼 보입니다.

Iterator it = map.entrySet().iterator(); 
    while (it.hasNext()) { 
     Map.Entry pair = (Map.Entry)it.next(); 
     System.out.println(pair.getKey() + " = " + pair.getValue()); 
     it.remove(); // ***** here ***** 
    } 

이렇게하지 마십시오.

기타 문제 :이 방법으로 정적 필드를 사용하는 것은 좋은 생각이 아니므로 오류를 디버그하기가 어려울 수 있습니다. 깨끗한 객체 지향 방식으로 서로 상호 작용하는 잘 캡슐화 된 클래스를 만드는 것이 훨씬 좋습니다.

+0

감사합니다. it.remove()를 제거한 후에도 문제가 없습니다. 그건 내 편이 멍청한 실수 였어. –