代码如下:
class thingsToRent
{
private static HashMap thingsToRent = new HashMap();
static
{
thingsToRent.put("V-1", new String( "Zumba workout video" ) );
thingsToRent.put("V-2", new String( "Pumping Iron video" ) );
}
public static String get( String serialEntered )
{这就是我需要返回租借字符串的地方,例如Zumba健身或Zumba,
我该怎么说呢?
return ?;我尝试过返回serialEntered,但这只给出了我想要的V-1或V-2
使用扫描仪进入控制台
}
}
class Video extends Thing
{
public Video( String serialEntered )
{
super( serialEntered );
}
public void getDescription( String serialEntered )
{
String theRentalFound = (String)thingsToRent.get( serialEntered );
if ( theRentalFound == null )
{
throw new IllegalArgumentException("Serial Number not found (" + serialEntered + ")");
}
else
{
System.out.println( "Video: " + theRentalFound );
}
}
}发布于 2012-12-05 14:14:51
return thingsToRent.get(serialEntered); 将会达到这个目的,但您不需要这样做,因为您已经在代码中实现了这一点。
发布于 2012-12-05 14:38:04
首先,总是对接口进行编码。将private static HashMap thingsToRent = new HashMap();更改为private static Map thingsToRent = new HashMap();
您的命名约定也是混乱的,将类名更改为类似于RentalItems的名称,将get方法更改为getRentableItem在该方法中,您需要使用提供的键访问映射:
public static String getRentableItem( String serialEntered )
{
return thingsToRent.get(serialEntered);
}请注意,您将需要添加coode来处理项目不存在时发生的事情-我将把它留给您来决定该做什么。
https://stackoverflow.com/questions/13717340
复制相似问题