why does my question and photo does not have same result - java

I'm trying to make an android quiz game that randomizes my questions and an images to help answer the question.. but the random values does not return the same after 2 attempts in the game.. randomNum is the int that i used for getting random number.. i'd like both the question to sync..
Random random = new Random();
//get random number between 0 to 9.
int randomNum = random.nextInt(quizArray.size());
//image
imageView.setBackgroundResource(image[randomNum]);
//pick quiz
ArrayList<String> quiz = quizArray.get(randomNum);
//set question and answer
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
//remove question
quiz.remove(0);
Collections.shuffle(quiz);
//set Choices
btn1.setText(quiz.get(0));
btn2.setText(quiz.get(1));
btn3.setText(quiz.get(2));
btn4.setText(quiz.get(3));
//remove quiz from quizArray
quizArray.remove(randomNum);
}

When you remove the quiz from your quizArray with this quizArray.remove(randomNum); you need also to remove the related image from image[] table, i suggest that you use a List of image instead of table so you can also use image.remove(randomNum); after quizArray.remove(randomNum);
I hope this helps

as B.M said, it looks like you're removing the quiz from quiz array but you're not removing the image from the image array - this is causing their indexes to be off.
Maybe you want to try using a HashMap of (quiz, image), and then grab a pair from the map with the random index.

Why don't you create a Question class with fields for questionString, answerString, and image. Then you can create a list of Question objects and simply removing the Question from the list will remove all associated question data.
class Question {
public final String questionString;
public final String answerString;
public final byte[] image;
public Question(String question, String answer, byte[] image) {
questionString = question;
answerString = answer;
this.image = image;
}
}
...
List<Question> questions = new ArrayList<>();
//Populate questions however
//I would suggest reading the questions from an XML file
//Instead of static array declarations for ease of use in the future
System.out.println(questions);
questions.remove(0);
System.out.println(questions);

Related

Cannot resolve symbol - ArrayList, Java

I'm writing a code in JAVA that is going to be a Lucky Wheel Game. The game at this stage takes a number as input to start the wheel to turn, get a random element from a collection of prizes and outputs the price. As you can see the code below, I created an array and added it's elements to the ArrayList. The player have 3 turns and at each turn he gets a random price (element) from the ArrayList. Sounds good, but I'm stuck. The problem is, for some reason I get the error of "Cannot resolve symbol 'wheel'. I use IntelliJ IDEA. I just started coding so I'm sure there's gonna be more errors after I resolve this one. But first, I want to solve this, then I can continue the game and add more to it. Thanks for all the answers!
Here's the code:
import java.util.*;
public class Game {
public static void func1(String[] prizes) {
ArrayList<String> wheel = new ArrayList<>(5);
//Adds array elements to ArrayList
Collections.addAll(wheel, prizes);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
String[] prizes = {"Television", "iPhone", "Microwave", "Ventilator", "Gift Card"};
func1(prizes);
int turn = scanner.nextInt(1);
int tries = 0;
int index = randomGenerator.nextInt(wheel.size()); // I get the error here
//int wheel = wheel.size();
while(tries < 3) {
turn = scanner.nextInt(1);
System.out.println("You won a" + wheel.get(index)); // and here too
tries++;
}
}
}

Issues saving data from a text file into an array list

Hello to anyone reading this, I've spent a couple hours now trying to figure out the root of a problem I've been having with an array list in a JavaFX trivia program I'm writing. I've finally narrowed down where the issue is, I just can't figure out what's causing it. Basically, I have a while loop that keeps reading lines of code until it reaches the end, and that works. At the end of each loop, I add the data I read to an ArrayList in the form of an object, that holds the data I read. It works, as when I print one of the parameters from the object at each index in the array list, it works. However, the moment I step outside of the while loop, every single index of the ArrayList holds the exact same data, and it is always the final question I saved for.
Here is the code:
while ((line = questionStream.readLine()) != null) {
// The question
String inquiry = line;
// The first possible response
line = questionStream.readLine();
String[] responses = new String[4];
responses[0] = line;
// The second possible response
line = questionStream.readLine();
responses[1] = line;
// The third possible response
line = questionStream.readLine();
responses[2] = line;
// The fourth possible response
line = questionStream.readLine();
responses[3] = line;
// The fact to display once the question has been answered
line = questionStream.readLine();
String fact = line;
// Space in between questions
questionStream.readLine();
// Adding the question
questions.add(new Question(inquiry, responses, fact));
Console.print(questions.get(temp).getInquiry());
temp++;
}
questionStream.close();
for (int i = 0; i < questions.size(); i++) {
Console.print(questions.get(i).getInquiry());
}
And the output is as follows:
How many countries border France?
What sea creature has 3 hearts?
The Simpsons is the longest running tv series. What is the name of the janitor?
What was the product of the first ever TV advertisement?
What TV series features a reference to or a picture of Superman in almost every episode?
How many castaways were on Gilligans Island?
How many castaways were on Gilligans Island?
How many castaways were on Gilligans Island?
How many castaways were on Gilligans Island?
How many castaways were on Gilligans Island?
How many castaways were on Gilligans Island?
How many castaways were on Gilligans Island?
So I'm really confused how the ArrayList holds all of the proper data perfectly, right until it exits the while loop, where it then only ever holds whatever the final question is in the text file.
Thanks for the help!
The problem is that you are not using instance variables in your Question class but class variables. That means your Question class should look like this in order to work as expected:
package trivia.questions;
public class Question {
// Data fields, don't use static!
private String inquiry;
private String[] answers;
private String fact;
private String correctAnswer;
...
/**
* Overloaded constructor
*
* #param inquiry the question
* #param answers the answers
* #param fact the cool fact for the correct answer
*/
public Question(String inquiry, String[] answers, String fact) {
this.inquiry = inquiry;
this.answers = answers;
this.fact = fact;
}
Using static for the variables will make that this variable is shared between all instance of your Question variable.
In each iteration you print out the current state which seem to be okay but after you finished you print out multiple time the same state which is shared between your different copies of class Question.
This is one major concept in object oriented programing in Java.

Click just ones

I have a JTextPane to display questions call Qus, I have 4 JLabel, A, B, C, D. And five questions on different pages. When you select the correct answer a,b,c,or d, 10 point is added to a JLabelcall Counter.
But my problem is, it time u click a,b,c,d it keeps adding 10 again, again, and again. I just want it to add 10 once on each page, if answer is correct on next page, it should add another 10 not multiple 10 on a page or answer, that will be a cheat.
Here is the code
// To display the result
string preval = Counter.get text()+" ";
Counter.setText("0");
//Pls note Counter is to display result in the GUI
//Now the question method
Public void init() {
Call question==0;
}
//First Question
If(callquestion==1) {
Qus.setText(" 1+1");
A.setText("A) 2");
B.setText("A) 8");
C.setText("A) 9");
D.setText("A) 10");
}
//Answer, let's assume the answer is A// note A, B, C, D are all JLables
Private void AmouseClicked(java.awt.event.MouseEvent evt) {
If(callquestion==1 && D.isFocusable()) {
Int d= Integer.parseInt(Counter.getText());
Int e= 10;
Int f=d+10;
Counter.setText(f+" ");
}
}
Please note this is just 1 question and answer. In my project I have 20 of this. I just want each button to add 10 once, and adding it on multiple clicks Thanks
Since you're going for one question at a time, why not reuse the page?
:)
First, we create a Question class...
class Question{
String question;
String answer1, answer2, answer3, answer4;
int userAnswer;
int correctAnswer;
boolean scoredPoints;
Question(String q, int correct, String a1, String a2, String a3, String a4){
this.question = q;
this.correctAnswer = correct;
this.answer1 = a1;
this.answer2 = a2;
this.answer3 = a3;
this.answer4 = a4;
}
}
Then we can create the question...
Question q1 = new Question("1+1",1,"2","4","6","8");
//constructor is question, correct answer, ans 1, 2, 3, 4.
Then create a list of Questions...
ArrayList<Question> questions = new ArrayList<>();
And add the Questions to the list...
questions.add(q1);
Then you do the same things you'd do to present the question, however, you'd reference questions.get(x) where x is the question number (minus one, since array index 0 is equal to object 1).
When a user presses a button, such as A, you call your actionlistener and invoke:
questions.get(x).scoredPoints = true; //prevents cheating
questions.get(x).userAnswer = buttonNumber; //sets user question answer
x in this case is the current question number.
This way you can have a continuous stream of questions, their answers will be recorded and checked, and they cannot "cheat".
I guess what the problem is: The AmouseClicked method gets called whenever a mouseevent occures (mouse_pressed, mouse_down, mouse_release). So this should do the trick.
If(callquestion==1 && D.isFocusable())
needs to be
If(callquestion==1 && D.isFocusable() && evt.getModifiersEx()==MouseEvent.MOUSE_PRESSED)
Instead of storing the points directly use a map (question, answer) to store in which question what answer the user gave:
// somewhere in your main programme
List<Integer> userAnswers;
List<Integer> correctAnswers;
...
// at programme startup initialise to #answers
userAnswers = Arrays.toList(new Integer[20]); // create list full of null
correctAnswers = new ArrayList<Integer>();
for(int i = 0; i < 20; ++i)
correctAnswers.add(0); // set all correct answers to #a (change this accordingly)
...
// when user answers question #q with answer #a
userAnswers.set(q, a); // set answer at #q to #a
Counter.setText(getScore() + " "); // update the counter every time the list changes!
...
// getScore counts up the awarded points for all questions
private int getScore() {
int sum = 0;
for(int q = 0; q < correctAnswers.size(); ++q) {
int expected = correctAnswers.get(q); // assume initialised
Integer actual = userAnswers.get(q); // may be null
if(actual != null && actual == expected)
sum += 10; // or have a third list indicating how many points each question awards
}
}
This has other advantages like you being able to tell the user in the end exactly which answers he got right and which ones he got wrong.
If I understand you correctly, I believe this is a better solution for your problem:
What you do in your setup:
JLabel a = new JLabel()
a.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
aclicked();
}
});
JLabel b = new JLabel()
b.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
bclicked();
}
});
//do this for c and d as well
The methods aclicked and bclicked is where you check if the right answer is given, and if so, award the points.

Best way to store temporary QuestionID-AnswerID data

I'm developing a quiz app and I want to find an efficient way to save user's answers.
Each quiz has 30 questions and all I need to save is:
questionNumber, questionId and answerId and either the answer is correct or not.
I thought an array will be a good solution. Example:
Each row represents a question (questionNumber). The first column represents the questionId and the second answerId. The third column will contain either 0 (incorrect) or 1 (correct).
The third column (correct) is needed to sum the number of correct answers (it's faster to sum the third column instead of checking each answer any time).
This isn't a SQL table - this info is temporary and will be destroyed as soon as the user finishes the quiz.
I want to know if you have any other solutions, maybe better.
Thank you!
Why not a class?
class Answer
{
private int questionID;
private int answerID;
private boolean correct;
public Answer(int questionID, int answerID, boolean correct)
{
this.questionID = questionID;
this.answerID = answerID;
this.correct = correct;
}
}
And an ArrayList
List<Answer> answers = new ArrayList<Answer>();
Then use
Answer answer = new Answer(1, 2, true);
answers.add(answer);
With an Array you will need to fix the array size every time you add a question with an ArrayList you can add as much questions as you want without care about the array size.
Anyway, if you questions will be always 30 you can create an Array too without problems.
About performances, well i don't see problems about speed/memory.

How to run a new Random nextInt everytime you do something in java? [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
So I am making a game (http://www.sharkinggame.tk) and I have to make a new Random Number each time I do such a thing, like, cast a fishing pole to see how long you are going to wait. So this is what I have which I belive should work.
public int generateNewRandomNumber() {
Random r = new Random();
int nextInt = r.nextInt(10000);
return nextInt;
}
I already tried just saying return r.nextInt(10000); which didnt work either.
If you want a random integer up to some constant, as in
doSomething(randomNumberUpToConstant());
The correct way to do that is
public class EnclosingClass{
Random r = new Random();
final int MAX_RANDOM_VALUE = 10000;
public void myMethod(){
doSomething(r.nextInt(MAX_RANDOM_VALUE));
}
}
Declare Random r = new Random(); once, statically. Then use that r wherever you need it. Do not keep recreating new instances.
Think of the Random object as a well - you dig one well and keep going back to it for water, you don't dig a new well every time you want a drink.
By not working, I assume you get an error. That would result if you didn't add import java.util.Random; to the beginning of your file. Also, note that it is better to create the Random once. Your code will become something like this:
import java.util.Random;
class SomeClass{
Random r;
public SomeClass(){
r = new Random();
}
public int getRandomNumber(){
return r.nextInt(10000); //numbers in the range [0,10000)
}
}
However, it doesn't really make sense to make a class like that. I'd just recommend using an instance of Random where you need it.
public class MyClass{
private final Random r = new Random();
private static final int RANGE = 10000;
public int generateNewRandomNumber(){
r.nextInt(RANGE);
}
}

Categories

Resources