2017-02-22 65 views
0

Я хочу, чтобы объединить эти два текстовых файлаобъединить два списка массива в TreeMap в Java

Driver подробности текстового файла:

AB11; Angela 
AB22; Beatrice 

Journeys текстовый файл:

AB22,Edinburgh ,6 
AB11,Thunderdome,1 
AB11,Station,5 

И я хочу мой вывод должен быть только именами и где человек был. Это должно выглядеть так:

Angela 
    Thunderdone 
    Station 

Beatrice 
    Edinburgh 

Вот мой код. Я не уверен, что я делаю неправильно, но я не получаю правильный результат.

ArrayList<String> names = new ArrayList<String>(); 
TreeSet<String> destinations = new TreeSet<String>(); 

public TaxiReader() { 

    BufferedReader brName = null; 
    BufferedReader brDest = null; 

    try { 

     // Have the buffered readers start to read the text files 
     brName = new BufferedReader(new FileReader("taxi_details.txt")); 
     brDest = new BufferedReader(new FileReader("2017_journeys.txt")); 

     String line = brName.readLine(); 
     String lines = brDest.readLine(); 

     while (line != null && lines != null){ 

      // The input lines are split on the basis of certain characters that the text files use to split up the fields within them 
      String name [] = line.split(";"); 
      String destination [] = lines.split(","); 

      // Add names and destinations to the different arraylists 
      String x = new String(name[1]); 
      //names.add(x); 

      String y = new String (destination[1]); 
      destinations.add(y); 


      // add arraylists to treemap 
      TreeMap <String, TreeSet<String>> taxiDetails = new TreeMap <String, TreeSet<String>>(); 
      taxiDetails.put(x, destinations); 

      System.out.println(taxiDetails); 

      // Reads the next line of the text files 
      line = brName.readLine(); 
      lines = brDest.readLine(); 

     } 

    // Catch blocks exist here to catch every potential error 
    } catch (FileNotFoundException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     // Finally block exists to close the files and handle any potential exceptions that can happen as a result 
     } finally { 
      try { 
       if (brName != null) 
        brName.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

} 


public static void main (String [] args){ 
    TaxiReader reader = new TaxiReader(); 
} 
+3

Добро пожаловать на переполнение стека! Похоже, вам нужно научиться использовать отладчик. Пожалуйста, помогите нам с некоторыми [дополнительными методами отладки] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Если у вас все еще есть проблемы после этого, пожалуйста, не забудьте вернуться с более подробной информацией. –

+1

Может захотеть заглянуть в ['BufferedReader # lines()'] (http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--) и [try- с-ресурсов] (https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) –

ответ

1

Вы читаете 2 файла параллельно, но не думаю, что это будет работать слишком хорошо. Попробуйте прочитать один файл за раз.

Также вы можете переосмыслить свои структуры данных.

Первый файл относится к key «AB11» к value «Angela». Карта лучше, чем ArrayList:

Map<String, String> names = new HashMap<String, String>(); 

String key = line.split(",")[0]; // "AB11" 
String value = line.split(",")[1]; // "Angela" 
names.put(key, value) 
names.get("AB11"); // "Angela" 

Аналогично, второй файл относится к key "AB11" к нескольким values "Thunderdome", "Станция". Вы можете также использовать карту для этого:

Map<String, List<String>> destinations = new HashMap<String, List<String>>(); 

String key = line.split(",")[0]; // "AB11" 
String value = line.split(",")[1]; // "Station" 

if(map.get(key) == null) { 
    List<String> values = new LinkedList<String>(); 
    values.add(value); 
    map.put(key, values); 
} else { 
    // we already have a destination value stored for this key 
    // add a new destination to the list 
    List<String> values = map.get(key); 
    values.add(value); 
} 

Чтобы получить вывод, который вы хотите:

// for each entry in the names map 
for(Map.Entry<String, String> entry : names.entrySet()) { 
    String key = entry.getKey(); 
    String name = entry.getValue(); 

    // print the name 
    System.out.println(name); 

    // use the key to retrieve the list of destinations for this name 
    List<String> values = destinations.get(key); 
    for(String destination : values) { 
     // print each destination with a small indentation 
     System.out.println(" " + destination); 
    } 
}