【问题标题】:Java: Call and Access array by its name, which is stored in a string inside different array or variableJava:按名称调用和访问数组,该名称存储在不同数组或变量内的字符串中
【发布时间】:2016-06-20 20:11:13
【问题描述】:

我有多个数组,根据存储在字符串中的用户输入,我需要访问相应的数组。 例如,用户输入“/kit food”并按下回车,字符串随后被子串化为“food”。 假设我已经有一个名为 food 的数组,我想将其中的所有项目打印到控制台中。 这是我正在尝试做的示例代码:

String[] food = {"apple","carrot","pickle"};
String[] tools = {"hoe","shovel","rake"};

userInput = "food";   //already sub stringed from "/kit food"

for(String item : userInput){   //I need it to access the array food
    System.out.println(item);
}

这可能吗?还是我应该为每个套件手动编写每个 if/else 语句?

【问题讨论】:

  • Java 变量不能这样工作。如果您需要将字符串关联到数组,请考虑使用Map
  • 您可以将数组添加到Map,每个数组的键都是它的名称。然后,只需使用objMap.get(userInput) 即可获取用户请求的数组。
  • Map接口是专门为这个案例设计的,看看docs.oracle.com/javase/tutorial/collections/interfaces/map.html
  • 此外,如果字符串是预定义的(“食物”、“工具”等)并且每次运行程序都不会更改,您可能需要查看基于枚举的命令模式的实现。

标签: java arrays string


【解决方案1】:

使用 Java 7

public static void main(String[] args) {
        String[] food = {"apple", "carrot", "pickle"};
        String[] tools = {"hoe", "shovel", "rake"};

        String userInput = "food";   //already sub stringed from "/kit food"

        Map<String, String[]> map = new HashMap<>();    
        map.put("food", food);
        map.put("tools", tools);

        for (String item : map.get(userInput)) {   //I need it to access the array food
            System.out.println(item);
        }
    }

【讨论】:

  • 感谢您的帮助,我还在 YouTube 上搜索了一些有关地图和哈希图的信息,以便更好地理解它们。 :)
猜你喜欢
  • 2012-05-17
  • 1970-01-01
  • 2016-04-13
  • 2011-01-28
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
相关资源
最近更新 更多