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]); }
Screen
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
Related
I am developing word scramble android app. I want to display the String of word in Sequence order but in below code it get random word from the dictionary. My question is how to change my code to get words from Dictionary in Sequence Order?
String[] dictionary=
{"One","Server","Terminate","Analyze","Finish","Start","Wonder","Slow"};
r = new Random(System.currentTimeMillis());
newGame();
// shuffle algorithm
private String shuffleWord(String word){
List<String> letters = Arrays.asList(word.split(""));
Collections.shuffle(letters);
String Shuffled="";
for (String letter : letters ){
Shuffled += letter;
}
return Shuffled;
}
private void newGame(){
// get random word from dictionary
currentWord= dictionary[r.nextInt(dictionary.length)];
// show the shuffled word
tv_word.setText(shuffleWord(currentWord));
// clear the textfield
et_guess.setText("");
// switch buttons
b_new.setEnabled(false);
b_check.setEnabled(true);
}
}
Actually you pick your word with a random position
r = new Random(System.currentTimeMillis());
using an integer random from 0 to ArrayOfWords lenght.
currentWord= dictionary[r.nextInt(dictionary.length)];
Why you dont try to make a counter instead?
int r = 0;
while (r<dictionary.length()) {
currentWord = dictionary[r];
r++;
}
Or I don't understand your answer. But there is the pseudo of what I understand.
I'm trying to create a random quiz app, but i'm facing a particular problem that i was not able to solve in the last 2 days.
I have all my questions and options inside of 2 different array of Strings. An int called flag which determines the progress of the quiz
int flag=0;
String allQuestions[]={"A","B","C","D","E","F","G","H","I","J"};
String allOptions[]={/*/Primeras opciones /*/"A","I","O",
/*/Segundas opciones/*/"E","O","I",
/*/Terceras opciones/*/"A","I","U",
/*/Cuartas opciones/*/"O","E","U",
*/Quintas opciones/*/"O","U","A",
/*/Sextas opciones/*/"I","U","E",
/*/Septimas opciones/*/"E","I","E"
/*/Octavas opciones/*/"A","I","U",
/*/Novenas opciones/*/"E","U","O",
/*/Decimas opciones/*/"A","O","U"};
This is how i pick the random numbers:
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);
I have my buttons linked and make their text change once the quiz activity is created.
question=(TextView)findViewById(R.id.QuizCharacter);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(number.get(flag)); // <------ having problems here?
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
Now, the randomizer works, the problem is that if the created random number is the first question A, then the app crashes.
I tried changing what i assume is the problematic line for
question.setText(allQuestions[number.get(0)]);
And instead of having a chance to randomize, it crashes every time.
Why is it happening and how can i fix it?
EDIT:
onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
correct = 0;
flag=0;
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i < 10; ++i) number.add(i);
Collections.shuffle(number);
String questionCounter = "Question number (flag+1): " + (flag + 1);//+ "\nnumber.get(flag)="+ number.get(flag);
TextView questionNumber;
questionNumber = (TextView) findViewById(R.id.questionNumber);
questionNumber.setText(questionCounter);
question.setText(allQuestions[number.get(0)]);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(allQuestions[number.get(flag)]);
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
}
Edit 2:
Thanks to Shadab Ansari for the answer. I forgot to initialize the variable question.
You are not storing anything at 0th index of number.
for (int i = 1; i <= 10; ++i) number.add(i); //Runs from 1 to 10
Your loop should change to -
for (int i = 0; i < 10; ++i) number.add(i); //Runs from 0 to 9
Also, according to the logs, "question" may be null. So please initialize all the views before using it.
I'm at my wit's end with this one! Here's some of my code:
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> indices;
int total = 10;
for(int c = 0; c < total; ++c)
{
score.add(c);
}
indices = new ArrayList<Integer>(total);
for(int c = 0; c < total; ++c)
{
indices.add(c);
}
Collections.shuffle(indices);
rando1 = indices.get(0);
int currentScore;
currentScore = score.get(indices.get(rando1));
Toast.makeText(getApplicationContext(),
"score location should be: " + rando1, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"score location is: " + currentScore, Toast.LENGTH_SHORT).show();
The toasts were to help me see what's going on. For some reason, no matter what I try, the rando1 and the currentScore will almost always be different numbers.
This is baffling me because I use rando1 on a number of other arrays (string arrays), and it always gets the correct items from the other arrays.
My question is why doesn't this get the same index item (the integer at whatever index) from the integer array as it does from the other string arrays. I've tried isolating just this code. I've tried changing various things. I've done a lot of testing. And the searches don't turn up anything too specific (but I've tried what I found there as well).
Desired output of the toasts: "score location should be: 3", "score location is: 3"
Actual output: "score location should be: 3", "score location is: 5" (replace 5 with any other number, because there's never a set pattern between what it should be and what it is).
Use the following code to get a random element ArrayList.
Random r = new Random();
currentScore = score.get(r.nextInt(score.size()))
If you want to the output, as you have, then change the following line:
currentScore = score.get(rando1);
ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.
I have a question regarding the following code
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(4);
String wordList[] = new String[4];
{
wordList[0] = "Red";
wordList[1] = "Blue";
wordList[2] = "Green";
wordList[3] = "Orange";
}
String wordToDisplay = wordList[randomInt];
This code works fine however I would like to know if it was possible to get it to not pick the same word two times in a row. For example, if it just selected "Red" then it would not pick "Red" again the next consecutive time. I read something about DISTINCT but I'm not sure if that's along the right path.
Here is the code for the button which uses this
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView = (TextView) findViewById(R.id.text_random_text);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
textView.setText(wordToDisplay);
Thankyou for your help
go for list and remove color once used:
private static ArrayList<String> arrayList = new ArrayList<String>();
private static Random random = new Random();
public static void fillList(){
arrayList.add("Red");
arrayList.add("Blue");
arrayList.add("Green");
arrayList.add("Orange");
}
public static String getNextRandomColor(){
if(arrayList.isEmpty()){
fillList();
}
return arrayList.remove(random.nextInt(arrayList.size()));
}
You can do this in two way (probably more but two that I can think of right now):
1) Create a function that uses a global variable to store the last generated random number.
It will look something like this:
int myRand(int i) {
int aux;
Random randomGenerator = new Random();
do {
aux = randomGenerator.nextInt(i);
} while (aux != lastRandGenerated);
lastRandGenerated = aux;
return aux;
}
, where lastRandGenerated is a global variable that you initialize to 0.
Then you use this function to generate random numbers.
2) You can create a class that has a function very similar to the one above and then instantiate an object of that class and use that to generate your random numbers. In the class create a static variable that will remember the last generated random number. Use that instead of the global variable.
The specifics are a bit out of my league but as a math problem there are 24 combinations (4 * 3 * 2 * 1). As heavy handed as this might sound, worst case you could work out all the combos and then pick a one out of 24 random.