2015-01-30 7 views
-3

Я задал этот вопрос, но, как я сказал, это был дубликат, который не был подобен. Я пытаюсь напечатать отдельную строку для моего метода printAllFlights, который печатает всю введенную пользователем информацию. Мои другие методы печатаются очень хорошо. Вот результат, который я пытаюсь достичь.Печать отдельной строки из того же объекта

Choose action: 
[1] Print planes 
[2] Print flights 
[3] Print plane info 
[x] Quit 
> 2 
HA-LOL (42 ppl) (HEL-BAL) 
HA-LOL (42 ppl) (BAL-HEL) 

Как мой код теперь я получаю вывод null (0) (HEL-BAL). Как я могу изменить его, чтобы отобразить правильный вывод. Любая помощь будет оценена по достоинству.

public class Airport { 
private String planeId; 
private int capacity; 
private String dest; 
private String dep; 

public Airport(String planeId,int capacity){ 
    this.planeId= planeId; 
    this.capacity = capacity; 
} 
public Airport(String planeId, String dep, String dest){ 
    this.dest= dest; 
    this.dep= dep; 

} 
public String getPlaneId(){ 
    return this.planeId; 
} 
public void setPlaneId(String planeId){ 
    this.planeId = planeId; 
} 
public int getCapacity(){ 
    return this.capacity; 
} 
public void setCapacity(int capacity){ 
    this.capacity = capacity; 
} 
public String getDestination(){ 
    return this.dest; 
} 
public void setDestination(String dest){ 
    this.dest = dest; 
} 
public String getDeparture(){ 
    return this.dep; 
} 
public void setDeparture(String dep){ 
    this.dep = dep; 
} 
public String toString(){ 
    return planeId + " (" + capacity + ")"; 
} 
public String secString(){ 
    return planeId + " (" + capacity + ")" + "(" + dest + "-" + dep; 
} 
} 

import java.util.ArrayList; 

public class FlightServices { 

private ArrayList<Airport> airport; 


public FlightServices() { 
    airport = new ArrayList<Airport>(); 

} 

public void add(String planeId, int capacity) { 
    airport.add(new Airport(planeId, capacity)); 
} 

public void addFlight(String planeId, String dest, String dep) { 
    airport.add(new Airport(planeId, dest, dep)); 
} 

public void printAllPlanes() { 
    for (Airport all : airport) { 
     System.out.println(all); 
    } 
} 

public void printAllFlights() { 
    for (Airport all : airport) { 
     System.out.println(all.secString()); 
    } 
} 

public void printPlanesInfo(String planeId) { 
    for (Airport info : airport) { 
     if (planeId.equals(info.getPlaneId())) { 
      System.out.println(info); 
     } 
    } 
} 

} 

import java.util.Scanner; 

public class UserInput { 

private Scanner reader; 
private FlightServices air; 


public UserInput(Scanner reader, FlightServices air) { 
    this.reader = reader; 
    this.air = air; 

} 

public void start() { 

    while (true) { 
     System.out.println("Choose operation: "); 
     System.out.println("[1] Add airplane"); 
     System.out.println("[2] Add flight"); 
     System.out.println("[3] Exit"); 

     int input = Integer.parseInt(reader.nextLine()); 
     if (input == 3) { 
      break; 
     } else if (input == 1) { 
      this.addPlane(); 
     } else if (input == 2) { 
      this.addFlight(); 
     } 
    } 

} 

public void addPlane() { 
    System.out.println("Give plane ID: "); 
    String id = reader.nextLine(); 
    System.out.println("Give plane capacity: "); 
    int capacity = Integer.parseInt(reader.nextLine()); 

    this.air.add(id, capacity); 
} 

public void addFlight() { 
    System.out.println("Give plane ID: "); 
    String id = reader.nextLine(); 
    System.out.println("Give departure airport code: "); 
    String dep = reader.nextLine(); 
    System.out.println("Give destination airport code: "); 
    String des = reader.nextLine(); 

    this.air.addFlight(id,dep,des); 

} 

public void printing() { 
    while (true) { 
     System.out.println("Choose operation: "); 
     System.out.println("[1] Print planes"); 
     System.out.println("[2] Print flights"); 
     System.out.println("[3] Print plane info"); 
     System.out.println("[4] Quit"); 

     int command = Integer.parseInt(reader.nextLine()); 
     if (command == 4) { 
      break; 
     } else if (command == 1) { 
      this.air.printAllPlanes(); 
     } else if (command == 2) { 
      this.air.printAllFlights(); 
     } else if (command == 3) { 
      this.addPlaneInfo(); 
     } 

    } 

} 

public void addPlaneInfo() { 
    System.out.println("Give plane ID: "); 
    String id = reader.nextLine(); 

    this.air.printPlanesInfo(id); 

} 

} 

import java.util.*; 
public class Main { 

public static void main(String[] args) { 
    Scanner reader = new Scanner(System.in); 
    FlightServices air = new FlightServices(); 


    UserInput ui = new UserInput(reader,air); 
    ui.start(); 

    System.out.println("Flight Service"); 
    System.out.println("----------"); 

    ui.printing(); 


} 

} 
+0

Под 'printFlights', вы имеете в виду' printAllFlights'? –

+0

@ AndyBrown Да, извините, printAllFlights(). –

ответ

4

Ok.

public void add(String planeId, int capacity) { 
    airport.add(new Airport(planeId, capacity)); 
} 

public void addFlight(String planeId, String dest, String dep) { 
    airport.add(new Airport(planeId, dest, dep)); 
} 

Вы хотите добавить некоторые Airport объекты к вашему airport с помощью addFlight() и другие, используя добавить(). Те, которые вы добавляете с помощью addFlight(), не имеют значений емкости, а те, которые используют add(), не имеют dest или dep. Ты видишь? Простое создание двух записей с одинаковыми planeId не будет сочетать их в вашем arraylist. При попытке печати некоторые значения будут нулевыми в зависимости от того, как вы добавили объекты Аэропорта.

EDIT: Одно решение я могу думать, в то время как изменения кода, как менее как possible-

public void add(String planeId, int capacity) { 
    int flag=0; 
    for(Airport air:airport) { 
     if(air.planeID.equals(planeID)) { 
      air.capacity=capacity; 
      flag=1; 
     } 

    } 
    if(flag==0) 
     airport.add(new Airport(planeId, capacity)); 
} 

И точно так же редактировать надстройку() функцию. Таким образом, вы можете иметь все соответствующие поля, заполненные одной записью.

Конечно, гораздо лучше было бы полностью перестроить ваши классы, но это должно сработать.

+0

@OP Вы имели в виду «Самолет» вместо «Аэропорт»? – Arkadiy

+0

Нет, это все Airport в коде, отправленном в вопрос! – vipluv

+0

О, хорошо. Я вижу это, но как я смогу распечатать, что пользователь вводит для AddFlight? В UserInput я могу запросить только planeId, отправление и пункт назначения. Но мне все еще нужно иметь возможность распечатывать эту емкость. –