创建一个双精度数组(用于状态的一行,用于国会大厦的一行),我试图在for循环中使用“ map.put”来保存数组“键(状态)”和“值(国会大厦)”到HashMap。在分配新的HashMap(hMap = getInfo();之后,使用来自用户输入的键时,我的输出返回“ null”。我不太确定自己在做什么错,但是我有种感觉,我为循环
public class HashMapProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
//Assign contents of map in getInfo to hMap
HashMap<String, String> hMap = getInfo();
//Prompting user to input a state (key)
System.out.print("Enter a state, or \"done\" when finished: ");
String state = input.next();
if(hMap.get(state) != "done")
System.out.println("The capital is "+ hMap.get(state));
}
public static HashMap<String, String> getInfo(){
//HashMap to save contents in
HashMap<String, String> map = new HashMap<>();
String x[][] = {
{"Alabama","Alaska","Arizona" ,"Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia",
"Hawaii" ,"Idaho" ,"Illinois" ,"Indiana" ,"Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland",
"Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey",
"New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington","West Virginia","Wisconsin","Wyoming"},
{"Montgomery","Juneau","Phoenix","Little Rock","Sacramento","Denver","Hartford","Dover","Tallahassee","Atlanta",
"Honolulu","Boise","Springfield","Indianapolis","Des Moines","Topeka","Frankfort","Baton Rouge","Augusta", "Annapolis",
"Boston","Lansing","St. Paul","Jackson","Jefferson City","Helena","Lincoln","Carson City","Concord","Trenton",
"Santa Fe","Albany","Raleigh","Bismarck","Columbus","Oklahoma City","Salem","Harrisburg","Providence","Columbia",
"Pierre","Nashville","Austin","Salt Lake City","Montpelier","Richmond","Olympia","Charleston","Madison","Cheyenne"}
};
//Saving contents in 'map'
for(int i = 0; i < x.length; i++) {
map.put(x[0][i], x[1][i]);
}
return map;
}
}
答案 0 :(得分:3)
有一些错误:
1)在for循环中,将i < x.length;
更改为i < x[0].length;
,否则您将仅运行2次循环。
2)不要使用!=
比较字符串。请改用equals()
。有关更多详细信息,请参见this。
3)您没有循环可重复要求用户输入。将main()
中的代码更改为:
Scanner input = new Scanner(System.in);
HashMap<String, String> hMap = getInfo();
String state = "";
do {
System.out.print("Enter a state, or \"done\" when finished: ");
state = input.next();
System.out.println("The capital is " + hMap.get(state));
} while (!state.equals("done"));
4)使用界面而非类。因此,更改
HashMap<String, String> hMap = getInfo();
到
Map<String, String> hMap = getInfo();
并更新方法签名以返回Map<String, String>
。
5)从Java 9开始,您可以像这样直接创建地图:
Map<String, String> m = Map.of(
"Alabama", "Montgomery",
"Alaska", "Juneau",
"Arizona", "Phoenix"
//and so on...
);