2012-06-14 3 views
0

나는 스탠포드에서 CS106A 과정을 수강하고 있는데, 그 중 하나는 특정 도시간에 이용 가능한 항공편 데이터베이스를 구축하는 것입니다. 도시에 대한 수업을 썼지 만 addDestination 메서드를 호출하면 처음으로 작동하고 두 번째 대상이 추가되면 ArrayList이 비어있게됩니다. 왜? 이 사람이 정말로 나를 잡았다. ArrayList를 올바르게 사용하기

import java.util.*; 
    //class for a city. destinations are stored in an ArrayList 
public class City { 

    //Constructor 
public City(String name){ 
    CityName = name; 
} 

//returns the name of the city 
public String getName(){ 
    return CityName; 
} 
    // takes in a destination and adds it to the ArrayList unless 
    //the destination already exists in which case it returns false. 
public boolean addDestination(String destination){ 
    if (destinations.indexOf(destination)==-1){ 
     destinations.add(destination); 
     return true; 
    } 
    else return false; 
} 

public Iterator<String> destIter(){ 
    Iterator<String> it =destinations.iterator(); 
    return it; 
} 

private ArrayList<String> destinations = new ArrayList<String>(); 
private String CityName; 
} 

다음은 도시의 데이터베이스를 생성하는 코드입니다. hmHashMap이며, 각 라인은 "샌프란시스코 -> 뉴욕"과 같이있는 txt 파일 읽기

BufferedReader rd = new BufferedReader(new FileReader(FileName)); 
    String line = ""; 
    while (line!=null){ 
     if (line.indexOf("->")!=-1){ 
      String From = line.substring(0, line.indexOf("->")-1); 
      String To = line.substring(line.indexOf('>')+2); 
      City city = new City(From); 
      if (hm.containsKey(From)==false)hm.put(From, city); 
      hm.get(From).addDestination(To); 

     } 
     line = rd.readLine(); 
    } 
+3

을 당신이 잘못의 ArrayList를 사용하는 것을 의미하지 않는다? – mre

+2

이것은 귀하의 질문에 대한 대답이 아니지만, 일반적인 프로그래밍 예절에서는 객체 변수를 맨 아래가 아닌 객체의 맨 위에 놓아야합니다. 또한 클래스 자체가 아니라 생성자에서 대상 ArrayList를 초기화해야합니다. 실제로 문제가 해결 될 수도 있지만 확실하지 않습니다. – MattS

+4

'.addDestination()'과'.destIter()'에 대한 호출을 보여줄 수 있습니까? – Tenner

답변

0

도시 목적지 목록이 비어있는 이유를 모르겠습니다. 귀하의 축 어적 코드를 디버깅하고 그것은 나를 위해 일했습니다.

대상을 city에서 확인하지 않으려면 hm.get(From)을 다시 확인하십시오. 이미 발견 한 도시가있는 경우 다시 언급하지 않는 도시를 만들고있는 것입니다.

다소 더 효율적 while - 블록은 다음과 같습니다

while (line != null) { 
    if (line.indexOf("->") != -1) { 
     String From = line.substring(0, line.indexOf("->")-1); 
     String To = line.substring(line.indexOf('>')+2); 

     if (! hm.containsKey(From)) { 
      hm.put(From, new City(From)); 
     } 
     hm.get(From).addDestination(To); 
    } 
} 
+0

로컬 변수 이름에 소문자로 시작하는 이름을 지정하는 것이 좋습니다 (예 : 'from','to'). – Tenner

+0

나는 도시에서 목적지를 확인하고 있었다! 무리 감사. 괜찮 았어. –

+0

당신을 진심으로 환영합니다. 괜찮으 시다면,이 대답을 upvote 받아 받아들이십시오. 다행이야! – Tenner

0

도시는 목적지를 포함를? 모든 것이 일어날 것 같아요. 라인 private ArrayList<String> destinations = new ArrayList<String> 때문에 클래스 인스턴스가 아닌 도시 인스턴스 용 멤버를 만들었습니다. 즉, 각 인스턴스에는 arraylist가 있지만 모든 대상을 하나로 묶는 arraylist 만 있으면됩니다. 비어 있습니다. 당신이 만든 두 번째 도시에 대한 arraylsit이기 때문에 더 구체적으로 말하자면, 실제로 그렇게되는지를 판단하는 주요 방법을 찾아야합니다.

+1

OP가 정확했습니다. 각 도시에는 여행 할 수있는 목적지가 하나 이상 있습니다. 따라서 City의 각 인스턴스에는 대상의 ArrayList가 있어야합니다. – Tenner

0

상단에 인스턴스 변수를 두는 것 이외에 코드가 작동합니다.