Java 通过询问用户名称来调用字符串数组
我正在写一个程序,可以给一个班级的多项选择题评分 我想将每个答案键存储为一个字符串数组,然后让用户输入一个字符串(练习的名称),该字符串将能够调用存储的字符串数组。从那里我知道如何将存储的字符串与用户的输入进行比较 我只是不知道如何获取输入字符串并使用它调用存储的字符串数组。有什么建议吗Java 通过询问用户名称来调用字符串数组,java,arrays,string,eclipse,input,Java,Arrays,String,Eclipse,Input,我正在写一个程序,可以给一个班级的多项选择题评分 我想将每个答案键存储为一个字符串数组,然后让用户输入一个字符串(练习的名称),该字符串将能够调用存储的字符串数组。从那里我知道如何将存储的字符串与用户的输入进行比较 我只是不知道如何获取输入字符串并使用它调用存储的字符串数组。有什么建议吗 谢谢 有很多方法可以做到这一点,这完全取决于您的代码设计,但一般来说,您可以通过使用简单的for循环来检索任何字符串[]的特定位置(假设这是一个长测试测试): 班级成绩{ 等级=新等级() String[]te
谢谢 有很多方法可以做到这一点,这完全取决于您的代码设计,但一般来说,您可以通过使用简单的for循环来检索任何字符串[]的特定位置(假设这是一个长测试测试): 班级成绩{ 等级=新等级()
String[]test1={“A”、“B”、“A”、“C”};
for(int i=o;i
使用单个数组存储每个答案效率极低。您需要的是一个可以存储值的对象,该值可以被键引用,而Hashmap
正好提供了这一点。研究下面的说明:
//Declare your hashmap:
Map <String, String> myAnswers = new HashMap<>();
/*
*Put the values you want
*The put method takes in two parameters, the key and the value.
*The key represents the name you want to call this element by.
*The value is the actual value (so to speak)
*/
myAnswers.put("firstQuestion", "Answer of firstQuestion");
myAnswers.put("secondQuestion", "Answer of secondQuestion");
myAnswers.put("thirdQuestion", "Answer of thirdQuestion");
//You can go on and on: key, value.. Just like we did up there.
我希望这有帮助。。快乐的编码 这很有帮助,但实际上我对输入部分比较困惑。我有一长串不同的测验答案键,存储为字符串数组。如何让用户输入所需测验的名称,以便程序调用我想要比较的答案键?这是我想要建立的下一步!将首先尝试使用字符串数组,然后尝试使用对象。在您的帮助下,我现在可以直接跳到对象。因此,当出现提示时,用户可以根据其键选择要使用的对象?完全正确!但在本例中,这些对象称为Hashmaps。。你所需要做的只是按键引用。。这完全符合你的目的。如果您仍然不了解Hashmap的工作原理,请阅读以下内容:使用2D数组或Hashmap。
//Declare your hashmap:
Map <String, String> myAnswers = new HashMap<>();
/*
*Put the values you want
*The put method takes in two parameters, the key and the value.
*The key represents the name you want to call this element by.
*The value is the actual value (so to speak)
*/
myAnswers.put("firstQuestion", "Answer of firstQuestion");
myAnswers.put("secondQuestion", "Answer of secondQuestion");
myAnswers.put("thirdQuestion", "Answer of thirdQuestion");
//You can go on and on: key, value.. Just like we did up there.
myAnswers.get(firstQuestion);