有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组如何在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";

共 (4) 个答案

  1. # 1 楼答案

    您可以使用HashMap(Map接口的实现),如下所示:

    Map<Integer,String> m = new HashMap<Integer,String>();
    m.add(1,"Orange");
    m.add(2,"Blue")
    System.out.println("The colour is "+m.get(1));
    
  2. # 2 楼答案

    这是一个通常通过使用Map来实现的问题;通常情况下HashMap<T,S>是适用的。出于您的考虑,您可以使用HashMap<Integer, String>

    编辑: 如果你想将其存储在一个数组中,你可以像在你的问题中那样使用一个数组,然后这样做

    int i = //read in number here
    System.out.println("Color is " + colorResList[i]);
    
  3. # 3 楼答案

    使用Map实现,由Integer键控,值为String

    Map<Integer, String> colors = new HashMap<Integer, String>();
    colors.put(2, "Orange");
    
  4. # 4 楼答案

    使用以下代码

    Map <Integer, String> map = new HashMap<Integer, String>();
    
    map.put(1,"One");
    map.put(2,"Two");
    map.put(3,"Three");
    map.put(4,"Four");
    
    System.out.println( map.get(3)); // get printed "Three"