1

我的代码如下所示:

public Flight{
String code;
char status;
char type;

   Flight(String code, char status, char type){
    this.code = code;
    this.status = status;
    this.type = type;
   }
 }


public Menu{
 Flight flight1 = new Flight("DL123",'A','D');
 Flight flight2 = new Flight("DL146",'A','I');
 flightMap.put("DL123", flight1)
 flightMap.put("DL146", flight2)
 }


  if(schedule.flightMap.containsKey(decision))
  {

  }

如果用户输入 DL123 并且 containsKey 返回 true,我只想返回flight1的对象属性。我怎么能做到这一点?我尝试过覆盖 toString 但因为 toString 只能作为字符串返回,所以我不知道如何返回作为字符的状态和类型属性。

请询问您是否需要更多信息!

4

4 回答 4

3

在类中定义getter方法Flight,然后:

 if(schedule.flightMap.containsKey(decision)){
   Fligth matchingFlight = schedule.flightMap.get(decision);
   String code = matchingFlight.getCode();
   char status = matchingFlight.getStatus();
   char type = matchingFlight.getType();
 }
于 2012-12-21T04:09:47.043 回答
1

航班航班 = schedule.flightMap.get(decision);

然后从飞行对象中,您可以检索所有值

于 2012-12-21T04:10:33.887 回答
1

你需要的是

Flight flight = schedule.flightMap.get(decision);

有了这些,您可以简单地访问对象,因为它们的可见性是默认的,就像这样

flight.code
flight.status

但更合乎道德的方式是像这样定义所有变量的getter和setter

public void setCode(String code)
{
     this.code = code;
}
public String getCode()
{
    return this.code;
}

这样你就可以使用这个来获取变量

String code = flight.getCode();

另请参阅

为什么在 java 中使用 getter 和 setter

于 2012-12-21T04:15:00.603 回答
0

我试图解决你的问题并得出结论。请参见下面的代码。

package com.rais;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Rais.Alam
 * @project Utils
 * @date Dec 21, 2012
 */


public class FlightClient
{
/**
 * @param args
 */
public static void main(String[] args)
{
    Map<String,Flight> flightMaps = new HashMap<String, Flight>();
    Flight flight1 = new Flight("DL123", "STATUS-1", "TYPE-1");
    Flight flight2 = new Flight("DL124", "STATUS-2", "TYPE-2");
    Flight flight3 = new Flight("DL125", "STATUS-3", "TYPE-3");

    flightMaps.put("DL123", flight1);
    flightMaps.put("DL124", flight2);
    flightMaps.put("DL125", flight3);

    System.out.println(getValue(flightMaps, "DL123"));


}


public static String getValue(Map<String,Flight> flightMaps, String key)    
{
    if(flightMaps !=null && flightMaps.containsKey(key))
    {
        return flightMaps.get(key).status;
    }
    else
    {
        throw new RuntimeException("Flight does not exists");
    }


    }
}

    class Flight
    {
    String code;
    String status;
    String type;
    /**
     * @param code
     * @param status
     * @param type
     */
    public Flight(String code, String status, String type)
    {
        super();
        this.code = code;
        this.status = status;
        this.type = type;
    }



}
于 2012-12-21T04:28:15.933 回答