[英]Java: Call and Access array by its name, which is stored in a string inside different array or variable
I have multiple arrays and depending on the users input, which is stored in a string, I need to access the corresponding array. 我有多个数组,根据用户输入,存储在一个字符串中,我需要访问相应的数组。 For example, the user types "/kit food" and presses enter, the string then gets sub-stringed to become "food".
例如,用户键入“/ kit food”并按下enter键,然后字符串被分弦成为“食物”。 Lets say I already have an array called food and I want to print all of the items inside of it out into the console.
假设我已经有一个名为food的数组,我想将其中的所有项目打印到控制台中。 here is an example code to what I'm trying to do:
这是我正在尝试做的示例代码:
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);
}
Would this be possible to do? 这有可能吗? or should I just manually code each if/else statement for every kit?
或者我应该只为每个工具包手动编写每个if / else语句?
Using Java 7 使用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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.