Reputation: 45
i would like to make the question random, and when i give the answer to compare if they are correct answer or not?? can someone give me a little help with it?
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random;
public class Main {
public static void main(String[] args) { String[] aa = { "question aa" }; String[] bb = { "question bb"}; String[] cc = { "question cc"}; String[] dd = { "question dd"}; String[] e = { "answer to question aa" }; String[] f = { "answer to question bb"}; String[] g = { "answer to question cc"}; String[] h = { "answer to question dd"}; // should be here the random question System.out.print("Enter your answer: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String userAnswer = null; try { userAnswer = br.readLine(); } catch (IOException ioe) { System.out.println("IO error trying to read your answer!"); System.exit(1); } System.out.println("Thanks for the answer, " + userAnswer);
}
Upvotes: 0
Views: 395
Reputation: 240996
class QuestionAnswer{
String q;
String a;
//getters/setters and const.
}
1 Create a DS as your Question set is smaller and advisable to keep in memory
List<QuestionAnswer> lst = new ArrayList<QuestionAnswer>();
lst.add(new QuestionAnswer("Question1","Answer1"));
lst.add(new QuestionAnswer("Question2","Answer2"));
lst.add(new QuestionAnswer("Question3","Answer3"));
2 Generate a random integer between 0 to list.size()
Random r = new Random();
int index = r.nextInt(lst.size());
3 Fetch question and print it and accept user;s answer
System.out.println(lst.get(index).getQ());
Scanner in = new Scanner(System.in);
// Reads a single line from the console
String answer = in.nextLine();
4 Compare user's answer with list
if(answer.equalsIgnoreCase(lst.get(index).getA())){
System.out.println("You are correct. !!");
}
Upvotes: 3
Reputation:
questions[random] and answers[random] should match
String[] aa = { "question aa" };
String[] bb = { "question bb" };
String[] cc = { "question cc" };
String[] dd = { "question dd" };
String[][] questions = { aa, bb, cc, dd };
String[] e = { "answer to question aa" };
String[] f = { "answer to question bb" };
String[] g = { "answer to question cc" };
String[] h = { "answer to question dd" };
String[][] answers = { e, f, g, h };
int min = 0;
int max = 5;
int random= 0;
random = min + (int) (Math.random() * max);
questions[random];
answers[random];
Upvotes: 0