displaying values from arrays - java

I have been working this quiz for a little while, however i am struggling to match the the question with the answer.
The following line and the others which are supposed to be display the answer actually display "[[ljava.lang.string;#40585b18" and slight variations.
quesAns4.setText("4) " + answers[3]) ;
i have tried changing the line now above to:
quesAns4.setText("4) " + answers[0][3]);
Obviously i want the answers to match the questions and the method above only displays 8 from array
{"3","5","8","9"}
So basically yeah for each change of question i want them to match. If the questions is "In seconds, how long does it take for a F1 car to stop when travelling at 300km/h?" the answers possible to be displayed should be 4,6,8,10 etc.
Any help/guidance would be appreciated thanks.
Full code below!
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MathsMultiplicationActivity extends Activity {
TextView quesnum;
TextView ques;
TextView anst;
TextView ans1;
TextView ans2;
TextView ans3;
TextView ans4;
ImageView cross;
ImageView tick;
Button nxt;
int qno = 1;
int right_answers = 0;
int wrong_answers = 0;
int rnd1;
int rnd2;
String [] questions = {"How much mph does the F-Duct add to the car?",
"What car part is considered the biggest performance variable?",
"What car part is designed to speed up air flow at the car rear?",
"In seconds, how long does it take for a F1 car to stop when travelling at 300km/h?",
"How many litres of air does an F1 car consume per second?",
"What car part can heavily influence oversteer and understeer?",
"A third of the cars downforce can come from what?",
"Around how much race fuel would be consumed per 100km?","The first high nose cone was introduced when?",
"An increase in what, has led to the length of exhaust pipes being shortened drastically?"};
String [] [] answers = {{"3","5","8","9"},
{"Tyres","Front Wing","F-Duct","Engine"},
{"Diffuser","Suspension","Tyres","Exhaust"},
{"4","6","8","10"},
{"650","10","75","450"},
{"Suspension","Tyres","Cockpit","Chassis"},
{"Rear Wing","Nose Cone","Chassis","Engine"},
{"75 Litres","100 Litres","50 Litres","25 Litres"},
{"1990","1989","1993","1992"},
{"Engine RPM","Nose Cone Lengths","Tyre Size","Number of Races"}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplechoice);
// Importing all assets like buttons, text fields
quesnum = (TextView) findViewById(R.id.questionNum);
ques = (TextView) findViewById(R.id.question);
anst = (TextView) findViewById(R.id.answertit);
ans1 = (TextView) findViewById(R.id.answer1);
ans2 = (TextView) findViewById(R.id.answer2);
ans3 = (TextView) findViewById(R.id.answer3);
ans4 = (TextView) findViewById(R.id.answer4);
nxt = (Button) findViewById(R.id.btnNext);
cross = (ImageView) findViewById(R.id.cross);
tick = (ImageView) findViewById(R.id.tick);
cross.setVisibility(View.GONE);
tick.setVisibility(View.GONE);
quesnum.setText("Question: " + qno + "/10");
final Button buttonAbout = (Button) findViewById(R.id.btnNext);
buttonAbout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
private void next() {
qno++;
change_question();
}
private void change_question() {
if(tick.getVisibility() == View.VISIBLE){
right_answers++;
}
if(cross.getVisibility() == View.VISIBLE){
wrong_answers++;
}
if(qno==questions.length){
}else{
cross.setVisibility(View.GONE);
tick.setVisibility(View.GONE);
rnd1 = (int)Math.ceil(Math.random()*3);
rnd2 = (int)Math.ceil(Math.random()*questions.length)-1;
ques.setText(questions[rnd2]);
if(questions[rnd2]=="x")
{
change_question();
}
}
questions[rnd2]="x";
if(rnd1==1){
TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers[0]) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers[1]) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers[2]) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer4);
quesAns4.setText("4) " + answers[3]) ;
}
if(rnd1==2){
TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers[2]) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers[0]) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers[1]) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer4);
quesAns4.setText("4) " + answers[3]) ;
}
if(rnd1==3){
TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers[1]) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers[2]) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers[0]) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer4);
quesAns4.setText("4) " + answers[3]) ;
}
}
});
//Answer 1 click functions
ans1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans1Action();
}
private void ans1Action() {
//enable_disable(0);
if(rnd1==1){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
//Answer 2 click functions
ans2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans2Action();
}
private void ans2Action() {
//enable_disable(0);
if(rnd1==2){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
//Answer 3 click functions
ans3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans3Action();
}
private void ans3Action() {
//enable_disable(0);
if(rnd1==3){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
//Answer 4 click functions
ans4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans4Action();
}
private void ans4Action() {
//enable_disable(0);
if(rnd1==4){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
}
}

This :
quesAns4.setText("4) " + answers[0][3]);
Works if this is the 1st question.
What you should do is to have in the change_question function the number of the question in parameter change_question(int questionNumber)
Then, when you set the texts, you use :
quesAns4.setText("4) " + answers[questionNumber][3]);
If your questions start at 0.
Else, you use :
quesAns4.setText("1) " + answers[questionNumber-1][0]);
quesAns4.setText("2) " + answers[questionNumber-1][1]);
quesAns4.setText("3) " + answers[questionNumber-1][2]);
quesAns4.setText("4) " + answers[questionNumber-1][3]);

To print arrays in a user-friendly manner, you need to loop over the array items or you can use the Arrays.deepToString method:
String yourPrinterFriendlyArray = Arrays.deepToString(answers[0]);
quesAns4.setText("4) " + yourPrinterFriendlyArray);

Related

user defined goClicked funtion is not executing.Suggest me a solution

"goClicked" function is a onClick function to the button "Go" but it is not executing when I click on the button "Go"( I am able to say this because the toast is not appearing ) until I comment the while loop in "goClicked" function. I am pasting the code for only 2 functions "goClicked" and "countdown" because they are the only functions that alter the variable "counterRunning".
public void goClicked(View view) {
afterGoPressed();
countDown();
correctCount = 0;
totalCount = 0;
TextView time = (TextView) findViewById(R.id.time);
while (counterRunning) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
}
public void countDown() {
counterRunning = true;
final TextView time = (TextView) findViewById(R.id.time);
final Button tryAgain = (Button) findViewById(R.id.tryAgain);
final TextView result = (TextView) findViewById(R.id.result);
final TextView score = (TextView) findViewById(R.id.score);
int secondsLeft = 30;
time.setText(secondsLeft+"");
CountDownTimer countDownTimer = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
time.setText(millisUntilFinished/1000 + "");
}
#Override
public void onFinish() {
tryAgain.setVisibility(View.VISIBLE);
result.setText("Your score: " + score.getText());
result.setVisibility(View.VISIBLE);
counterRunning = false;
}
}.start();
}
It is because you're using an infinite loop with the following code:
while (counterRunning) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
the code will blocking all other instruction until it found the counterRunning is changed to false inside the while block. But it never happened. Hence the infinite loop.

How to finish array question, it always repeating

Hi everyone I need help.
I have this code
I have 50 question string and I want if already 10 question appears then the game finish. thank you for your help
private Question mQuestion = new Question();
private String mAnswer;
private int mScore = 0;
private int mQuestionLenght = 5 ;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Score: " + mScore );
updateQuestion(r.nextInt(mQuestionLenght));
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(answer4.getText() == mAnswer){
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
} else {
gameOver();
}
}
});
}
private void updateQuestion(int num){
question.setText(mQuestion.getQuestion(num));
answer1.setText(mQuestion.getChoice1(num));
answer2.setText(mQuestion.getChoice2(num));
answer3.setText(mQuestion.getChoice3(num));
answer4.setText(mQuestion.getChoice4(num));
mAnswer = mQuestion.getCorrectAnswer(num);
}
private void gameOver(){
}
i have 50 question i want if user already answer 10 question game stop and show score. in that code it cant stop if they wrong answer game can stop but if user always right game load all question
In your Acitivty, add a counter attribute
private int numberOfQuestionsAsked = 0;
After each question asked, add 1 to your counter
if(answer4.getText().equals(mAnswer)){ //note : use .equals() and not == !
mScore++;
numberOfQuestionsAsked++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
}
After the user answered a question, check if the counterhas reached 10, if yes, go to gameOver
if(numberOfQuestionsAsked <= 10) {
gameOver();
}
In gameOver, reset the counter so the game can restart
numberOfQuestionsAsked = 0;
Your code should look like
private Question mQuestion = new Question();
private String mAnswer;
private int mScore = 0;
private int mQuestionLenght = 5 ;
private int numberOfQuestionsAsked = 0;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Score: " + mScore );
updateQuestion(r.nextInt(mQuestionLenght));
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(answer4.getText().equals(mAnswer)){ //note : use .equals() and not == !
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
numberOfQuestionsAsked++;
} else {
gameOver();
}
if(numberOfQuestionsAsked <= 10) {
gameOver();
}
}
});
}
private void updateQuestion(int num){
question.setText(mQuestion.getQuestion(num));
answer1.setText(mQuestion.getChoice1(num));
answer2.setText(mQuestion.getChoice2(num));
answer3.setText(mQuestion.getChoice3(num));
answer4.setText(mQuestion.getChoice4(num));
mAnswer = mQuestion.getCorrectAnswer(num);
}
private void gameOver(){
numberOfQuestionsAsked = 0;
}
Add a counter in your code like this :
Int counter = 0;
if(counter <= 10 ){
updateQuestion(r.nextInt(mQuestionLenght));
counter++;
} else {
gameOver();
}
Add this and check, hope it will work.
First of all, I would use:
View.OnClickListener listener = new View.onClickListener() {
#Override
public void onClick(View view) {
if(view instanceOf (TextView) && ((TextView)view).getText().toString().equals(mAnswer)){
mScore++;
score.setText("Score: " + mScore);
if(mScore >= 10) {
gameCompleted();//ToDo
} else {
updateQuestion(r.nextInt(mQuestionLenght));
}
} else {
gameOver();
}
}
};
Then, use this listener in every answer.
Futhermore, your random number may fail because it can be higher than 50 and can be a repeated answer and your text comparison is not recommended, you could use an object which assigns an id to the text.
Enjoy coding.

App Score from checkboxes

I'm coding a quiz app. When I clicked the score button to see if it worked, it showed I got 0 out of 5 right. I put in all the correct answers, but my code didn't tally anything up. What am I missing? I'm not sure what else to add and could really use the guidance as I am a new coder. I appreciate any help you can give.
int correctAnswers = 0;
// Start score
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
This will never be true
q4RightAnswer.equals(correctAnswers)
You need to compare matching types, not Strings to integers.
Assuming that's what you're trying to do, either parse the string or convert the int to a String.
You'll get zero printed if none of the checkboxes are marked or answers() is never called. For example, what's the difference between the answers method and the submitScore method? Both take a View parameter, so which one is actually assigned to the click event?
I would suggest doing something like
RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
Basically, define all views as class level variables, then immediately set them after a content view is available, then only calculate the score when the button is clicked (in other words, wait for user input). Also, reset the score each time the button is clicked.

equals method doesn't work when comparing TextView String

So I'm new to java and I'm trying to make quiz app as exercise. I kinda made one but it doesn't work:
public class QuizActivity extends AppCompatActivity {
TextView QuestionText;
Button button1;
Button button2;
Button button3;
Button button4;
ArrayList<Question> listOfQuestions;
int currentQuestion = 0;
Context context = this;
int NumberOfQuestions;
GameCreator game;
String totalCorrect = "";
String totalWrong = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
QuestionText = (TextView) findViewById(R.id.textJautajums);
button1 = (Button) findViewById(R.id.buttonOpcija1);
button2 = (Button) findViewById(R.id.buttonOpcija2);
button3 = (Button) findViewById(R.id.buttonOpcija3);
button4 = (Button) findViewById(R.id.buttonOpcija4);
NumberOfQuestions = Integer.parseInt(context.getString(R.string.JautajumuSkaits).toString());
game = new GameCreator(NumberOfQuestions);
listOfQuestions = game.makeQuestions();
Resources r = getResources();
int px1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 165, r.getDisplayMetrics());
button1.setWidth(px1);
button2.setWidth(px1);
button3.setWidth(px1);
button4.setWidth(px1);
Resources e = getResources();
int px2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 125, r.getDisplayMetrics());
button1.setHeight(px2);
button2.setHeight(px2);
button3.setHeight(px2);
button4.setHeight(px2);
if (currentQuestion == 0){
setQuestion(listOfQuestions.get(0));
}
button1.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button1.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button2.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button2.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button3.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button3.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button4.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button4.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
}
public void gajiens(String answer, Question thisQuestion){
if (currentQuestion < 14){
if (answer.equals(thisQuestion.getAnswer())){
totalCorrect += "Question: " + thisQuestion.getQuestion() + "\nYour Answer: " + answer + "\n";
} else {
totalWrong += "Question: " + thisQuestion.getQuestion()) + "\nYour Answer: " + answer + "\n";
}
currentQuestion++;
setQuestion(listOfQuestions.get(currentQuestion));
} else {
Intent intent = new Intent(this, EndActivity.class);
intent.putExtra("correct", totalCorrect);
intent.putExtra("wrong", totalWrong);
startActivity(intent);
}
}
public void setQuestion(Question kursh){
QuestionText.setText(kursh.getJautajums());
button1.setText(kursh.getOption1());
button2.setText(kursh.getOption2());
button3.setText(kursh.getOption3());
button4.setText(kursh.getOption4());
}
object Question is:
public Question(String Question, String Option1, String Option2, String Option3,String Option4, String correctAnswer){
Question = Question;
Option1 = Option1;
Option2 = Option2;
Option3 = Option3;
Option4 = Option4;
correctAnswer = correctAnswer;
}
Basically the problem is that App doesn't count the right answers. For some reason it most of the time uses the original text of TextView as ''correctAnswer''. Anyone has any idea what to do? I suspect since this isn't working properly this isn't particularly best approach so maybe someone can suggest a better one?
to compare the value of a TextView with a String you can do this as below
TextView tvAnswer = (TextView) findViewById(R.id.tvAnswer);
String correctAnswer = "Correct Answer";
if(correctAnswer.equals(tvAnswer.getText.toString()) )
{
//do something
}
else{
//do something
}

aplying onPostExecute to onClickListener

i have made program which works with AsyncTask it prints a list of the JSON data when program is executed, but the problem is that i want it to execute when i press the button. How do i get the results of AsyncTask into my onClickButtonListener ? How do i call AsyncTask from onClick?
Code:
public class Instillinger extends MainActivity {
DatabaseHelper myDb;
String navn;
String adresse;
String bilmere;
TextView visNavn;
TextView visAdresse;
TextView visBil;
EditText navnFelt;
EditText adrFelt;
EditText bilFelt;
Button lagreButton;
Button tilbakeButton;
Button visDataButton;
List<Bruker> brukere;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instillinger);
myDb = new DatabaseHelper(this);
// visNavn = (TextView) findViewById(R.id.visNavn);
visAdresse = (TextView) findViewById(R.id.visAdresse);
//visBil = (TextView) findViewById(R.id.visBil);
navnFelt = (EditText) findViewById(R.id.navnFelt);
adrFelt = (EditText) findViewById(R.id.adrFelt);
bilFelt = (EditText) findViewById(R.id.bilFelt);
lagreButton = (Button) findViewById(R.id.lagreButton);
tilbakeButton = (Button) findViewById(R.id.tilbakeButton);
//visDataButton = (Button) findViewById(R.id.visData);
brukere = myDb.getBrukere();
for(Bruker b: brukere){
String log = "Du er registrert som: "+ b.getNavn() + "\n" +
"Adresse: " + b.getAdresse() + "\n" +
"Bilmerke: " + b.getBilmerke() + "\n" +
"For å oppdatere informasjon fyll Alle feltene nede";
visAdresse.setText(log);
}
settInnData();
}
public void settInnData() {
lagreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDb.addContact(new Bruker("Giedrius","mldc","123","1"));
brukere = myDb.getBrukere();
for(Bruker b: brukere){
String log = "Du er registrert som: "+ b.getNavn() + "\n" +
"Adresse: " + b.getAdresse() + "\n" +
"Bilmerke: " + b.getBilmerke() + "\n" +
"Bilmerke: " + b.getState() + "\n" +
"For å oppdatere informasjon fyll Alle feltene nede";
visAdresse.setText(log);
}
//myDb.getContact(myDb.getCount()).toString();
}
});
}
}}
You can call your AsyncTask class inside your button listener by simply invoking new YourAsyncTaskName().execute(). Good Luck.

Categories