数组如何在Java数据结构中同时存储数字和相应的单词?
我不确定我是否正确使用了Java中的数组。如何将一个单词和一个数字存储在一起,以便在给定数字的情况下选择相应的单词
例如,假设数字2对应于“橙色”一词:
Prompt: "Enter number:"
Input: 2
Output: "Color is Orange."
我尝试使用数组:
String [] colorResList = new String[10] ;
int resCounter = 0 ;
// Assign values to elements in array.
colorResList[2] = "Orange";
# 1 楼答案
您可以使用HashMap(Map接口的实现),如下所示:
# 2 楼答案
这是一个通常通过使用
Map
来实现的问题;通常情况下HashMap<T,S>
是适用的。出于您的考虑,您可以使用HashMap<Integer, String>
编辑: 如果你想将其存储在一个数组中,你可以像在你的问题中那样使用一个数组,然后这样做
# 3 楼答案
使用Map实现,由
Integer
键控,值为String
:# 4 楼答案
使用以下代码