【问题标题】:Recall String Array by asking user for its Name通过询问用户的名称来调用字符串数组
【发布时间】:2018-04-02 00:50:37
【问题描述】:

我正在编写一个程序,可以对班级的多项选择题进行评分。

我想将每个答案键存储为一个字符串数组,然后让用户输入一个字符串(练习的名称),它能够调用存储的字符串数组。从那里我知道如何将存储的字符串与用户的输入进行比较。

我只是不知道如何获取输入字符串并使用它来调用存储的字符串数组。有什么建议吗?

谢谢!

【问题讨论】:

  • 使用二维数组或哈希图。

标签: java arrays string eclipse input


【解决方案1】:

使用单独的数组来存储每个答案是非常低效的。您需要的是一个可以存储 values 的对象,该对象可以由 key 引用,而 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);

我希望这会有所帮助.. 编码愉快!

【讨论】:

  • 这是我想要建立的下一步!将首先尝试使用字符串数组,然后尝试使用对象。在您提供的帮助下,我现在可以直接跳到对象。因此,当提示时,用户可以根据其键选择要使用的对象?
  • 没错!但在这种情况下,这些对象被称为 Hashmaps.. 您需要做的只是通过键来引用.. 它 100% 适合您的目的。如果您仍然不了解 Hashmap 的工作原理,请阅读以下内容:beginnersbook.com/2013/12/hashmap-in-java-with-example
【解决方案2】:

有很多方法可以做到这一点,这完全取决于您的代码设计,但通常您可以使用简单的 for 循环检索任何 String[] 的特定位置(假设这是一个很长的测试测验):

班级成绩{ 成绩成绩=新成绩();

String [] test1 = {"A", "B", "A", "C"};

for (int i = o; i < test1.length; i++) {
//this will retrieve every grade at every array position in order for 0 to 
however long the array is.
grades.get[i]
}
}

【讨论】:

  • 这很有帮助,但实际上我对输入部分更加困惑。我有一长串不同的测验答案键,存储为字符串数组。如何让用户输入所需测验的名称,以便程序召唤我想要比较的答案键?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多