gpt4 book ai didi

Java:通过名称调用和访问数组,该名称存储在不同数组或变量内的字符串中

转载 作者:太空宇宙 更新时间:2023-11-04 12:30:10 25 4
gpt4 key购买 nike

我有多个数组,根据存储在字符串中的用户输入,我需要访问相应的数组。例如,用户输入“/kit food”并按 Enter 键,该字符串就会被子字符串化为“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 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);
}
}

关于Java:通过名称调用和访问数组,该名称存储在不同数组或变量内的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37931029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com