gpt4 book ai didi

java - 具体如何从ArrayList中提取元素呢?

转载 作者:行者123 更新时间:2023-12-01 20:18:37 25 4
gpt4 key购买 nike

我的任务是开发一个程序,提示用户创建自己的问题和答案,并将其存储到 arrayList 中。此后,每当用户输入相同的问题时,程序就会自动提取答案。

到目前为止我所做的:我设法将问题和答案存储到 arrayList 中,但我不知道当用户询问他刚刚创建的问题时如何触发程序提取准确的答案。这是我的代码:

import java.util.ArrayList;
import java.util.Scanner;

public class CreateQns {

public static void main(String[] args) {
String reply;
ArrayList qns = new ArrayList();
ArrayList ans = new ArrayList();
System.out.println("Type 0 to end.");

do {
Scanner input = new Scanner (System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if(!reply.equals("0")) {
qns.add(reply);
System.out.println("Enter your answer ==>");
System.out.print("You: ");
ans.add(input.nextLine());
}
else {
System.out.println("<==End==>");
}
}while(!reply.equals("0"));
}

}

最佳答案

您可以使用HashMap<String, String>存储键/值用户输入一个问题,检查它是否在 map 中,如果是则打印答案,如果没有则询问答案并存储它:

public static void main(String[] args) {
String reply;
HashMap<String, String> map = new HashMap<>();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner(System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if (!reply.equals("0")){

if (map.containsKey(reply)) // if question has already been stored
System.out.println(map.get(reply)); // print the answer
else {

System.out.println("Enter your answer ==>");
System.out.print("You: ");
map.put(reply, input.nextLine()); // add pair question/answer
}
}else{
System.out.println("<==End==>");
}
} while (!reply.equals("0"));
}
<小时/>

但要直接回答您的问题,而不是 map.contains()你应该这样做:

int index;
if ((index = qns.indexOf(reply)) >= 0){
System.out.println(ans.get(index));
}

但它不如 map 方便,功能也弱

关于java - 具体如何从ArrayList中提取元素呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281632/

25 4 0