【发布时间】:2016-02-29 21:35:51
【问题描述】:
我使用哈希图创建了以下代码,以在记分牌中显示玩家。现在我遇到了一个问题。
最后,我已经实现了添加一个已经存在的播放器的代码,但是我无法显示一条提示该播放器已经存在的消息。
感谢任何帮助,我的意思是任何帮助。问我问题,让我们解决这些小问题。
package javamaptest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class JavaMapTest
{
public static void main(String[] args)
{
try
{
Map mplayer = new HashMap();
mplayer.put("Carlsen, Magnus", "Country:NOR, Rating:(2876), DOB:1990");
mplayer.put("Anand, Viswanathan", "Country:IND, Rating:(2804), DOB:1969");
mplayer.put("Caruana, Fabiano", "Country:ITA, Rating:(2803), DOB:1992");
mplayer.put("Nakamura, Hikaru", "Country:USA, Rating:(2799), DOB:1987");
mplayer.put("Topalov, Veselin", "Country:BUL, Rating(2798), DOB:1975");
mplayer.put("Grischuk, Alexander", "Country:RUS, Rating:(2780), DOB:1983");
mplayer.put("So, Wesley", "Country:USA, Rating:(2778), DOB:1993");
mplayer.put("Kramnik, Vladimir", "Country:RUS, Rating:(2777), DOB:1975");
mplayer.put("Giri, Anish", "Country:NED, Rating:(2776), DOB:1994");
mplayer.put("Aronian, Levon", "Country:ARM, Rating:(2776), DOB:1982");
mplayer.put("Ding, Liren", "Country:CHN, Rating:(2757), DOB:1992");
mplayer.put("Vachier-Lagrave, Maxime", "Country:FRA, Rating:(2754), DOB:1990");
mplayer.put("Karjakin, Sergey", "Country:RUS, Rating:(2753), DOB:1990");
mplayer.put("Navara, David", "Country:CZE, Rating:(2751), DOB:1985");
mplayer.put("Tomashevsky, Evgeny", "Country:RUS, Rating:(2749), DOB:1987");
mplayer.put("Li, Chao b", "Country:CHN, Rating:(2748), DOB:1989");
mplayer.put("Woitaszek, Radoslaw", "Country:POL, Rating:(2746), DOB:1987");
mplayer.put("Gelfand, Boris", "Country:ISR, Rating:(2744), DOB:1968");
mplayer.put("Adam, Michael", "Country:ENG, Rating:(2740), DOB:1971");
mplayer.put("Jakovenko, Dmitry", "Country:RUS, Rating:(2738), DOB:1983");
// Below I added a pre existing player
mplayer.put("Jakovenko, Dmitry", "Country:RUS, Rating:(2738), DOB:1983");
Iterator iter = mplayer.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry mEntry = (Map.Entry) iter.next();
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
// This I find a player with a given key
mplayer.get("Carlsen, Magnus");
mplayer.get("Anand, Viswanathan");
System.out.println("----------------------------------------------------------------------------");
System.out.println("Carlson, Magnus key information : " + mplayer.get("Carlsen, Magnus"));
System.out.println("Anand, Viswanathan key information : " + mplayer.get("Anand, Viswanathan"));
}
catch (Exception e) {
System.out.println(e.toString());
}
return
}
}
【问题讨论】:
-
main应该是void,所以不需要return。 -
那么您想要返回什么?为什么你让你的主要方法返回
boolean?通常main是一个void方法。至于剩下的问题:您应该在每个帖子中问 一个 问题,并在适当的情况下使用minimal reproducible example(此问题包含的代码比必要的多),并且不要呼吁不要投反对票。 -
我投票决定将此问题作为题外话结束,因为它提出了三个问题。应该编辑它以提出一个 clear 问题。
-
您调用
mplayer.get("Carlsen, Magnus")但不捕获返回值。为什么? --- 要查看密钥是否存在,请调用containsKey(),然后使用if语句来控制您的操作。
标签: java hashmap return maps return-value