Reputation: 102
I want my program to ask random questions and have dynamic answers But it only asks random questions and I need a dynamic answer
Button btn_1,btn_2; TextView text; setContentView(R.layout.activity_main); btn_1=findViewById(R.id.btn_1); btn_2=findViewById(R.id.btn_2); text=findViewById(R.id.text); int min = 1; int max = 3; Random r = new Random(); int rand = r.nextInt(max - min + 1) + min; String[]question={"What is Name Color Sky ?", "What is Name Color Night?", "What is Blood Color?" }; String[]answer={"Blue ", "Black", "White", "Red", "Green" ,"Purple" }; text.setText(question[rand]); }
Upvotes: 1
Views: 68
Reputation: 2182
Try this:
btn_1.setText(answer[r.nextInt(6)])
btn_2.setText(answer[r.nextInt(6)])
This will choose 2 random colours independently.
Edit
To ensure that the correct answer is available, you will need to store the correct answers somewhere. I strongly recommend making a Question class that stores the string for the question and the correct answer, but you can achieve the desired effect with just an array of the answers, e.g.:
Button[] answerButtons = new Button[] {btn1, btn2};
int numButtons = 2;
String[] correctAnswers = new String[] {"Blue", "Black", "Red"}; // you have a space after blue, remove it
List<String> answersDisplayed = Arrays.asList(new String[numButtons]);
int indexOfCorrectAnswer = random.nextInt(numButtons);
answersDisplayed.set(indexOfCorrectAnswer, correctAnswers[rand]); // the number used to pick the question earlier
for (int i = 0; i < numButtons; i++){
if (correctAnswers[rand] == null) {
// rand was used to pick the question, so pick the answer that goes with it
// pick a random answer that hasn't come up yet
String incorrectAnswer = answer[random.nextInt(6)];
while (answersDisplayed.contains(incorrectAnswer)){
incorrectAnswer = answer[random.nextInt(6)];
}
answersDisplayed.set(i, incorrectAnswer);
}
answerButtons[i].setText(answersDisplayed.get(i));
}
This will work for any number of buttons
Upvotes: 1