XxS0ul678 XxS0ul678 - 3 years ago 76
Java Question

How to extract elements from ArrayList specifically?

I am tasked to develop a program that prompts users to create their own questions and answers, which will be stored into the arrayList. After that, whenever the user types the same question, the program will automatically extract the answer.

What I did so far: I manage to store the questions and answers into the arrayList, but I have no idea how to trigger the program to extract exact answer when the user asked the question that he had just created. Here are my codes :

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"));
}

}

Answer Source

You may use a HashMap<String, String> which stores Key/value The user enter a question, check if it is in the map, if yes print the answer, if not ask the answer and store it :

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"));
}

But to answers directly to what you ask, instead of the map.contains() you should do :

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

But that is less convenient, less powerfull than Map

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download