我收到的错误是...... “put(Object,Object)在UIManager中无法应用于(int)”
Random rand = new Random();
int randomNum = rand.nextInt(7)+1;
Map <String, Integer> colours = new HashMap<>(); {{
put("red",1);
put("white",2);
put("purple",3);
put("orange",4);
put("pink",5);
put("yellow",6);
put("green",7);
put("blue",8);
}};
Map <String, Integer> answer = new HashMap<>(); {{
put(randomNum);
put(randomNum);
put(randomNum);
put(randomNum);
}};
我正在尝试设置一个充满颜色的地图,然后将4种随机颜色应用于新地图。它会允许任何颜色等粉红色粉红色粉红色,红色黄色白色白色......我在哪里出错?
答案 0 :(得分:1)
我认为你的设计并不正确。也许你应该这样做:
Random rand = new Random();
Map<Integer, String> colours = new HashMap<>();
colours.put(1, "red");
colours.put(2, "white");
colours.put(3, "purple");
colours.put(4, "orange");
colours.put(5, "pink");
colours.put(6, "yellow");
colours.put(7, "green");
colours.put(8, "blue");
List<String> answer = new ArrayList<String>();
answer.add(colours.get(rand.nextInt(7) + 1));
answer.add(colours.get(rand.nextInt(7) + 1));
answer.add(colours.get(rand.nextInt(7) + 1));
answer.add(colours.get(rand.nextInt(7) + 1));
答案 1 :(得分:0)
您只放置整数,必须使用<String, Integer>
地图格式:
Map <String, Integer> answer = new HashMap<>(); {{
put(randomNum);
put(randomNum);
put(randomNum);
put(randomNum);
}};
尝试这样:
Random rand = new Random();
Map <String, Integer> colours = new HashMap<>();
colours.put("red", 1);
colours.put("white", 2);
colours.put("purple", 3);
colours.put("orange", 4);
colours.put("pink", 5);
colours.put("yellow", 6);
colours.put("green", 7);
colours.put("blue", 8);
//creating a Set variable for colours keySet
Set<String> keySet = colours.keySet();
//creating a list variable for getting the key by putting value
ArrayList<String> keyList = new ArrayList<String>(keySet);
Map <String, Integer> answer = new HashMap<>();
int randomNum = rand.nextInt(7)+1;
for(int i = 1; i <= 8; i++){
//creating a random number between 1 to 7
randomNum = rand.nextInt(7)+1;
//first getting the key by value and putting in map as key
answer.put(keyList.get(randomNum), randomNum);
//showing the mapped value as key color name
System.out.println(answer.get(keyList.get(randomNum)));
}
请在那里添加一个String对象作为键,以删除错误。