'is it possible to input a question into the console, and have it return the correct answer?
First let's look at 3 Example questions and Answers:
String[] questions = new String[3];
questions[0] = "What is the first letter in the alphabet?";
questions[1] = "What is two plus two?";
questions[2] = "What planet do we live on?";
String[] answers = new String[3];
answers[0] = "A";
answers[1] = "four";
answers[2] = "Earth";
So the idea is that the code has all the questions that I could ask, and I want the console to return back the correct answer that corresponds to the correct question
So an Example that works:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.equalsIgnoreCase(questions[1])){
System.out.println(answers[1]);
} else {
System.out.println("Question is unknown");
}
With this only if type "What is two plus two" it will answer "four" However, that is only because the question is specifically written in the code
So if I want all of the questions I have written it multiple times:
if(input.equalsIgnoreCase(questions[0])){
System.out.println(answers[0]);
} else {
System.out.println("Question is unknown");
}
if(input.equalsIgnoreCase(questions[1])){
System.out.println(answers[1]);
} else {
System.out.println("Question is unknown");
}
if(input.equalsIgnoreCase(questions[2])){
System.out.println(answers[2]);
} else {
System.out.println("Question is unknown");
}
What I need is for the console to look through all the questions in one go. I don't know how to either have the input equal quesions[0 through x(however many there are)] or somehow make the if/else statements in a for loop so i don't have to write them all individually, I feel like a method could help, but I'm not too sure where to go from this point.
Thank you to whoever decides to help me, I feel like it's close but I'm just missing a little something :/
Solution 1:[1]
If I understand your question correctly, I believe you could use a for loop and compare the input to the question at each index
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] questions = new String[3];
String[] answers = new String[3];
//Explained lower down
boolean questionFound = false;
//Iterate through the whole questions list
for (int i = 0; i < questions.length; i++) {
//Compare input question to each question in the list and if
//it is equal then print out the answer
if (input.equalsIgnoreCase(questions[i])) {
System.out.println(answers[i]);
questionsFound = true;
break;
}
}
//And then for the question not found, I'm sure there is a better way, but all I can think about is a boolean flag right now.
if (!questionFound) {
System.out.println("Question not found");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
