Randomized questions and answers - java

I'm making a quiz game with 3 different choices. First, I created a list with a total of 17 questions and answers. Then to make sure that the order is ramdomized every time I play the game I will Collections.shuffle(MyList) the whole list at the beginning.
My structure:
I'm picking a question at a randomized position in the list. But, the question is randomized between 0-2, so if I get "1", I will get the question like this Mylist.get(1).getQuestion().
The choices/answers are at the position 0-2 in the list. (The first choice will be: Mylist.get(0).getAnswer(), the second Mylist.get(1).getAnswer() and the third Mylist.get(2).getAnswer()) By doing this, one of the answers will be correct since the index of the question is also between 0-2. And to keep the right choice in a randomized position.
However, the problem is, every time I answer a question, this question will be removed from the list. (Mylist.remove(1)) So, in the end, there will be less than 3 items left and I won't have 3 unique answers. My goal is to have 3 different choices with randomized order on every question, and one of them is, of course, correct. I'm new into programming and don't really know how to fix it. (Everything is in Netbeans).
Thanks in advance!

So you have 17 questions and each question has a correct answer, and you need to show each of these questions with three proposed answers, one of which is correct and other two are wrong (but these are correct answers to other questions)?
Shuffle the list only once, at the beginning of the program. Then, use a for loop to present the questions in order. Don't remove answered questions; the loop will ensure that each question is asked only once. Since the list is shuffled, the user will not be able to predict questions.
Then, fill in the proposed answers: put the correct answer at a random position, and fill the remaining positions with random other answers (use the while loop to ensure that these answers are different from the correct one and from each other).
Something like:
Collections.shuffle(MyList);
for(int i=0; i<MyList.size(); i++){
System.out.println(MyList.get(i).getQuestion();
Answer[] answers=new Answer[3];
int correct=(int)(Math.random()*3);
answers[correct]=MyList.get(i).getAnswer();
int j=i, k=i;
while( j==i ){
j = (int)(Math.random()*MyList.size());
}
answers[(correct+1)%3] = MyList.get(j).getAnswer();
while( k==i || k==j ){
k=(int)(Math.random()*MyList.size());
}
answers[(correct+2)%3] = MyList.get(k).getAnswer();
System.out.println("Answers:");
for(int t=0;t<3;t++){
System.out.println(answers[t]);
}
}

Related

Understanding a coding challenging in finding the first duplicate value in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)

two arrays are always equal [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code
for (int i=0; i<tini.length; i++){
tini[i].tempLabel.setText("Temp: "+ Float.toString(tempArray[i]) +"°" );
out_status[i] = tini[i].alarm;
frame.statusLabel.setText("Connetction: OK, String: OK");
}
System.out.println("old: " + Arrays.toString(out_status_old));
System.out.println("new: " + Arrays.toString(out_status));
if (Arrays.equals(out_status, out_status_old) ){
System.out.println("UGUALI");
}
out_status_old = out_status;
the resulting arrays are always equal. I cannot understand the reason.
Using a Button in JFrame, in a GUI interface i can modify the value of alarm, but both the old value and the actual one change at the same time!
When you access and then update the elements of one array, you're also updating the elements of the other array because they are referencing the same objects. You need to create separate items within each array while populating the arrays.
You left out an important part of your program which is where you're actually populating these arrays. Odds are, you are not doing a deep copy.
Deep copy of an object array
The line out_status_old = out_status; does not create a copy of the array. You have just two variables, out_status and out_status_old, pointing to the same array.
If you want to create a proper copy of the array, you can e.g. use Arrays.copyOf (or one of its variants).

Adding up values of items in an ArrayList [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
ive hit a road block and im stuck with a question on my work.
Here is the question:
Provide an implementation of the getLoad method that adds up the individual weights of
the items in the items list and returns the total.
The items list is:
ArrayList<Item> items;
Ive done what i thought was right but for some reason its not working.
Any help on what is wrong, or if what im doing is wrong? thanks
#Override
public int getLoad() {
int load = 0; //declare the variable
for (Item i : items) { // for each item in the list of items
load = load + i.getWeight() ; // load equals the weight of the item and adds on
}
return load; //returns it
}
The one thing I could see going wrong is if getWeight() returns a double. In that case, you should make int load: double load instead
With the limited information you've provided here, I can only take a wild guess that the problem is either:
The list items is empty even though it shouldn't be. Make sure that Items actually get added to the list! Use a debugger or a printed message to find out if the item list is empty on getLoad().
Weights for each Item are not assigned correctly, so getWeight() returns zero for each of them. Make sure that each Item added to the list actually gets assigned its proper weight.
Posting more code would help us give a better answer.

Subroutine dice rolling assignment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm just learning subroutines and I'm still very, very amateurish at this. My assignment asks me to toss two dice, display what the dice display (random numbers), display total of the two die, and let the program continue until 7 or 11 is the total. We haven't done anything on arrays, so I don't know if I should use them or not.
Also, I was going to use a for loop, but how would I get the program to stop at either 7 or 11 using it? Should I try another loop?
Please help guide me on what I have to do! I'm very confused about how to make the methods and put them into the main method. Just an explanation would do!
Thank you!
Here's the pseudocode for this problem. I won't give you the actual code but this will set you in the right direction:
Loop forever: {
Integer A = Random #1-6
Integer B = Random #1-6
Integer total = A + B
If total == 7 or total == 11 BREAK from the loop
Print total
}
Some more hints: Looping forever is usually achieved by setting up a while loop whose condition is always true. For example, while (true) or while (1 == 1).
Also, look into the java.util.Random class for generating a random number. It's really straightforward and it's good to start learning how to use the Java docs early in your learning process.
I would suggest a while loop. In your case,
instantiate the two dice
while the total isn't either 7 or 11 {
roll again
}
print out the result of the roll that wasn't either 7 or 11.
should be a reasonable starting point for you. I won't go into too much detail so that you still get the chance to implement the idea yourself and learn from it. If you don't know how to simulate a dice roll, #Kon's answer is helpful.
You may write a subroutine that returns the total number and call it in main method in while-loop
class Rolling-dice {
public static int roll() {
// roll the first dice and display the number
// roll the second dice and display the number
// return total`number
}
public static void main(String[] args) {
int result = roll();
// while result not 7 or 11 call roll()
}
}

loop through using variables in selenium [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a requirement in which I gettext from a site and then later on use that in a loop so it can continue to click elements base on that variable. This works but only loops for 5 times and the number of times it should click is like 100 and or above. here is a sample of the code
String vText= driver.findElement(By.xpath(")).getText();
System.out.println(vText);
int vEle= vText.length();
for (int i=0; i<vEle; i++){
driver.findElement(By.xpath("")).click();
What am I doing wrong please help me out
Thanks,
Mediha
You might need to verify locators from where you are taking text 100 times. If it is same for all 100 elements it would work.
Have you tried with findElements method?
//It will return the List of webelements which has same locator
List<WebElement> elements=driver.findElements(By.xpath(""));
//Now iterate through List and do the required operation with each individual element
for(WebElement ele:element)
{
ele.getText(); //It will print innertext of each element
ele.click(); //It will click on each element
}
I think that the error in your example is in this line:
int vEle= vText.length();
And later on your loop is:
for (int i=0; i<vEle; i++){
Which means youl loop is going to happen only that many times as the text is long. So if the text was Hello then the loop will happen only 5 times.
Thanks to Santosh and Pavel,
I actually found another approach although I will look in to the code you sent me Santosh. But here is the code I came up with and please give me comments as to if is this the best approach.
String vText driver.findElement(By.xpath("")).getText();
//This will split the output from the slash and the output looks like 1/120
final String[] splitted = vText.split("\\D+");
//Here it will parse that output to an integer type and start with the first location
final int slideCount = Integer.parseInt(splitted[1]);
for (int i=0; i<slideCount; i++) {
driver.findElement(By.xpath("")).click();
}

Categories

Resources