Weird error + How to make this code more efficent? - java

as soon as I use method Game(), my app crashes, why?
Also I'd like to know if it's possible to make my code shorter in terms of space it takes & better.
Code:
package com.aleksei.etb;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class ETBetaActivity extends Activity implements View.OnClickListener {
Button answer_1,
answer_2,answer_3,
answer_4,main;
TextView q_textview,
TextView tip;
private String aString[];
private int i1 = 0;
private int correct = 0;
private boolean alive = false;
MediaPlayer button_click;
private String[] questions ={"Question 1" , "Question 2","Question 5"};
private String[] answers_correct ={"Correct answer 1", "Correct answer 2","Correct answer 3","Correct answer 4","Correct answer 5"};
List<String> question_list = new ArrayList<String>();
List<String> answer_list_correct = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getData();
}
#Override
public void onClick(View view) {
button_click = MediaPlayer.create(this, R.raw.button_click);
button_click.start();
switch(view.getId()){
case R.id.button5: //main
if(!alive)
alive = true;
break;
case R.id.button1: //answer_1
if(alive == false)
return;
if(correct(1))
correct++;
break;
case R.id.button2: //answer_2
if(alive == false)
return;
if(correct(2))
correct++;
break;
case R.id.button3: //answer_3
if(alive == false)
return;
if(correct(3))
correct++;
break;
case R.id.button4: //answer_3
if(alive == false)
return;
if(correct(4))
correct++;
break;
default:
break;
}
Game();
}
private boolean correct(int button){
try {
for (int i = 0; i < answers_correct.length; i++){
if(button == 1 && aString[0] == answers_correct[i]
|| button == 2 && aString[1] == answers_correct[i]
|| button == 3 && aString[2] == answers_correct[i]
|| button == 4 && aString[3] == answers_correct[i])
return true;
}
}
catch(Exception ex){
System.out.println(ex);
}
return false;
}
private void Game(){
if(i1 > questions.length) //no more questions
return;
main.setText("Next");
try {
String answer_list[][] = {
{answers_correct[i1], "Answer 1-2" , "Answer 1-3" , "Answer 1-4"},
{answers_correct[i1], "Answer 2-2" , "Answer 2-3" , "Answer 2-4"},
{answers_correct[i1], "Answer 3-2" , "Answer 3-3" , "Answer 3-4"},
{answers_correct[i1], "Answer 4-2" , "Answer 4-3" , "Answer 4-4"},
{answers_correct[i1], "Answer 5-2" , "Answer 5-3" , "Answer 5-4"}};
Collections.shuffle(Arrays.asList(answer_list[i1]));
answer_1.setText(answer_list[i1][0]);
answer_2.setText(answer_list[i1][1]);
answer_3.setText(answer_list[i1][2]);
answer_4.setText(answer_list[i1][3]);
aString[0] = answer_list[i1][0];
aString[1] = answer_list[i1][1];
aString[2] = answer_list[i1][2];
aString[3] = answer_list[i1][3];
q_textview.setText(questions[i1]);
}
catch(Exception e){
System.out.println(e);
}
tip.setText(correct);
/*questions = question_list.toArray(new String[question_list.size()]);
answers_correct = answer_list_correct.toArray(new String[answer_list_correct.size()]);
question.setText(questions[i1]);
answer_list_correct.remove(questions[i1]);
question_list.remove(questions[i1]);*/
i1++;
}
private void getData(){
//Getting the data
main = (Button) findViewById(R.id.button5);
answer_1 = (Button) findViewById(R.id.button1);
answer_2 = (Button) findViewById(R.id.button2);
answer_3 = (Button) findViewById(R.id.button3);
answer_4 = (Button) findViewById(R.id.button4);
q_textview = (TextView) findViewById(R.id.question);
tip = (TextView) findViewById(R.id.answ1);
//Making the buttons, actually work
main.setOnClickListener(this);
answer_1.setOnClickListener(this);
answer_2.setOnClickListener(this);
answer_3.setOnClickListener(this);
answer_4.setOnClickListener(this);
//Resets the text
//Note to self: Replace with another ContectView
main.setText("Begin!");
answer_4.setText("");
answer_3.setText("");
answer_2.setText("");
answer_1.setText("");
/* for(String x : questions) {
for(String y : answers_correct){
answer_list_correct.add(y);
question_list.add(x);
Collections.shuffle(answer_list_correct);
Collections.shuffle(question_list);
}
} */
}
}
Best regards.

In Game(), you check i1 > questions.length at the top, but try q_textview.setText(questions[i1]); near the bottom. If i1 == questions.length, that would throw an ArrayIndexOutOfBoundsException (hope I remembered the name correctly), make it i1 >= questions.length. Also, you use i1 as index for answers_correct and answer_list, that won't be out of bounds for the pasted questions and answers_correct, but might be for the real (unlikely, though, you won't have more questions than answers, would you?).
In correct, your if statement
if(button == 1 && aString[0] == answers_correct[i]
|| button == 2 && aString[1] == answers_correct[i]
|| button == 3 && aString[2] == answers_correct[i]
|| button == 4 && aString[3] == answers_correct[i])
return true;
could be shortened to
if (aString[button-1] == answers_correct[i]) return true;
(unless button can have values < 1 or > 4, then you would need to check for button >= 1 && button <= 4 too). However, using == to compare Strings is dangerous and almost certainly wrong. == compares the equality of references, so string1 == string2 is true only if both refer to the same String instance. If, as seems to be the case, all your Strings come from string literals in the source code, it will kind of work because then there is only one instance for each literal, but if outside Strings could enter the game, you must use equals to compare Strings. Use equals also in those cases where == would (sort of accidentally) work.

Related

What does array do in this code?

I am studying on udemy. I was writing the code of XOX game. I think all of us know XOX game. My code is working but i didn't understand what does this code do ?
for (int [] winningPosition : winningPositions){
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2)}
The code which is the i dont get is above. Please help me with understand that.
{ package com.example.anild.xox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// 0 = yellow, 1 = red
int activePlayer = 0;
boolean gameIsActive = true;
//2 means unplayed
int [] gameState = {2,2,2,2,2,2,2,2,2};
int [][] winningPositions = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
public void dropIn(View view) {
ImageView counter = (ImageView) view;
int tappedCounter = Integer.parseInt(counter.getTag().toString());
if(gameState[tappedCounter] == 2 && gameIsActive) {
//burada tappedCounterdaki sayıyı çekiyor yani tag'i daha sonra gamstate[] dizisine atıyor. Ve zaten hepsi 2 if koşulu sağlanıyor
//Bir asağısında bu kural değişiyor. Bu alınan tag gametate'te artık 0 olarak saklanıyor :)
gameState[tappedCounter] = activePlayer;
counter.setTranslationY(-1000f);
if (activePlayer == 0) {
counter.setImageResource(R.drawable.yellow);
activePlayer = 1;
} else {
counter.setImageResource(R.drawable.red);
activePlayer = 0;
}
counter.animate().translationYBy(1000f).rotation(360).setDuration(300);
for (int [] winningPosition : winningPositions){
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2){
//someone has won
gameIsActive = false;
String winner = "Red";
if(gameState[winningPosition[0]] == 0){
winner = "Yellow";
}
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText(winner + "has won !");
LinearLayout layout = (LinearLayout)findViewById(R.id.playAgainLayout);
layout.setVisibility(View.VISIBLE);
}
else {
boolean gameIsOver = true;
for(int counterState : gameState) {
if (counterState == 2) {
gameIsOver = false;
}
if (gameIsOver) {
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText("it's a draw");
LinearLayout layout = (LinearLayout)findViewById(R.id.playAgainLayout);
layout.setVisibility(View.VISIBLE);
}
}
}
}
}
}
public void playAgain(View view) {
gameIsActive = true;
LinearLayout layout = (LinearLayout)findViewById(R.id.playAgainLayout);
layout.setVisibility(View.INVISIBLE);
// 0 = yellow, 1 = red
activePlayer = 0;
for(int i = 0; i < gameState.length; i++) {
gameState[i] = 2;
}
GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);
for(int i = 0; i < gridLayout.getChildCount(); i++) {
((ImageView) gridLayout.getChildAt(i)).setImageResource(0);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
}
Answering based on the question posed below my comment:
At it's most fundamental, the format for that for loop is
for('one object' : 'group of objects')
Now then, under ordinary circumstances you'd use something along the lines of:
for(String oneString : arrayOfStrings)
Based on your question, it appears as if you are unaware that you can statically specify an array of values by putting them inside braces. For example:
String[] arrayOfStrings = {"zero", "one", "two"};
That produces exactly the same result as:
String[] arrayOfStrings = new String[3];
arrayOfStrings[0] = "zero";
arrayOfStrings[1] = "one";
arrayOfStrings[2] = "two";
You could loop over that with for(String string : arrayOfStrings)...
Going back to your original code - they have embedded braces inside braces, which is how you declare a multi-dimensional array. So the following:
int [][] winningPositions = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
Produces the same array as:
int[][] winningPositions = new int[8][3];
winningPositions[0][0] = 0;
winningPositions[0][1] = 1;
winningPositions[0][2] = 2;
...
winningPositions[7][0] = 2;
winningPositions[7][1] = 4;
winningPositions[7][2] = 6;
With me so far?
The full "winningPositions" variable is an object of type array, whose content is itself a sequence of arrays. Okay, so now when you do your loop that you don't understand, this:
for (int [] winningPosition : winningPositions)
Each item in the array "winningPosition" is itself an array - as I just said - so the "one object" resolves to the inner array, which has 3 elements, while the outer has 8.
Does that help?
On a side note: Code like that is either aimed at new programmers, or else is written by someone that doesn't understand OO programming. It's worthwhile to understand how it works, it is not necessarily meant to be emulated. Or at least by the time you know I'm wrong about that, you'll know why I'm wrong.
for (int [] winningPosition : winningPositions)
Iterates through the array called winningPositions. Each iteration has the variable called winningPosition which is an int array of length 3.
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] &&
gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2)
checks that all the positions are owned by the same player and the last part gameState[winningPosition[0]] != 2 checks that the line isn't empty.
EDIT:
#ChrisParker explains this line very well in the comments. for (int [] winningPosition : winningPositions)
The for loop is iterating through the array and checking each of the conditions inside the if statement, IF all of them are true then the code will go inside the IF loop otherwise it will skip over and continue.
Cheers

if statement with not equals in Java android

I need to take the three strings and make sure that they are the same and that they are not null or empty.
This code is working fine in a Java online compiler but not in Android Studio.
int i = 0; ...
B1 = (Button) findViewById(R.id.B1);
B2 = (Button) findViewById(R.id.B2);
B3 = (Button) findViewById(R.id.B3);
B1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if (i==0){
B1.setText("X");
i++;}
else if (i==1){
B1.setText("O");
i = 0;}
}
});
// the same for B2 and B3...
String SB1 = B1.getText().toString();
String SB2 = B2.getText().toString();
String SB3 = B3.getText().toString();
if (SB1.equals(SB2) && SB2.equals(SB3) && !SB1.equals("") ){
Win.setText("win");
}
If you want to make sure that two strings are same or not...
String one = "RAMESH";
String two = "RAMESH";
if((one.contentEquals(two))
{
Toast.makeText(getActivity(), "Strings are same", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Strings are NOT SAME", Toast.LENGTH_SHORT).show();
}
You can check in your case like :
if(SB1.contentEquals(SB2) && SB2.contentEquals(SB3))
{
if(!SB1.equals(""))
{
Win.setText("win");
}
}
Hope it helps
Check the condition as
String SB1 = B1.getText().toString().trim();
String SB2 = B2.getText().toString().trim();
String SB3 = B3.getText().toString().trim();
if(SB1.equals(SB2) && SB2.equals(SB3) && !SB1.isEmpty()){
Win.setText("win");
}
But your condition getting false because, all buttons having empty text / no text and it get false due to SB1.isEmpty() and when you performs click on B1 button, it changes the text on it, which does not match condition for equality of string. So make sure to change text of B2 and B3 buttons too.

I try to create a vocabulary loop in android

I am trying to make an app that alike vocabulary card.
I have an Answer array(array size = 4).
I am creating random an english word then I am adding true value of english word in answer array and I am removing true value of english word in turkish array in order to not use again in random.I am doing same things to other answer array include wrong value.
Problem is that array size is going to 0.for example my total array 20 .when I remove true value,array size is going to 19-18-17... per click then program close.
Here is my code:
package de.murattekinlive.pwords;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class WordsActivity extends AppCompatActivity {
TextView textView;
TextView deneme;
DataBase dataBase;
Button btn_r1,btn_r2,btn_r3,btn_r4;
String [] TR_WORDS;
String [] EN_WORDS;
String [] Answer;
int control_id = 0;
int random ;
Random control;
Random rnd;
int tr,en;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_words);
textView = (TextView) findViewById(R.id.textView);
deneme = (TextView) findViewById(R.id.textView3);
dataBase = new DataBase(getApplicationContext());
rnd= new Random();
btn_r1 = (Button)findViewById(R.id.button_random1);
btn_r1.setOnClickListener(new myClickListener());
btn_r2 = (Button)findViewById(R.id.button_random2);
btn_r2.setOnClickListener(new myClickListener());
btn_r3 = (Button)findViewById(R.id.button_random3);
btn_r3.setOnClickListener(new myClickListener());
btn_r4 = (Button)findViewById(R.id.button_random4);
btn_r4.setOnClickListener(new myClickListener());
ArrayList<Words> enWordlist = (ArrayList<Words>) dataBase.allEnWords();
ArrayList<Words> trWordlist =(ArrayList<Words>) dataBase.allTrWords();
TR_WORDS = new String[trWordlist.size()];
EN_WORDS = new String[enWordlist.size()];
for(int i=0;i<enWordlist.size();i++){
EN_WORDS[i] =enWordlist.get(i).getWORD().toString();
TR_WORDS[i] =trWordlist.get(i).getTR1().toString();
}
tr = new Random().nextInt(TR_WORDS.length);
/*btn_r1.setText(TR_WORDS[en]);
btn_r2.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r3.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r4.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);*/
ReStart();
}
private class myClickListener implements View.OnClickListener{
public void onClick(View v){
switch ( v.getId() ) {
case R.id.button_random1:
break;
case R.id.button_random2:
break;
case R.id.button_random3:
break;
case R.id.button_random4:
break;
default:
break;
}
WordsActivity.this.ReStart();
}
}
public void ReStart(){
Answer = new String[4];
control = new Random();
control_id = control.nextInt(4);
en = new Random().nextInt(EN_WORDS.length);
final List<String> newTRList = new ArrayList<>();
textView.setText(EN_WORDS[en]);
final int sayi1,sayi2;
sayi1 = TR_WORDS.length;
Collections.addAll(newTRList,TR_WORDS);
// I added true turkish word in answer array
for(int i=0;i<TR_WORDS.length;i++){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
TR_WORDS = newTRList.toArray(new String[newTRList.size()]);
//I added another values in answer array and I want to remove values that is used because
//I dont want to see same value in answer array.
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
sayi2 =TR_WORDS.length;
deneme.setText(sayi1+"/"+sayi2);
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
for(int j=0;j<=3;j++){
if(j==0){
btn_r1.setText(Answer[j].toString());
}
else if(j==1){
btn_r2.setText(Answer[j].toString());
}
else if(j==2){
btn_r3.setText(Answer[j].toString());
}
else if(j==3){
btn_r4.setText(Answer[j].toString());
}
}
}
}
Change your for loop to:
for(int i=TR_WORDS.length; i >=0 ;i--){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
And all the other ones that include a remove in a similar a fashion.

if statment not working properly in android

hello guys im newbie in android i want just to change the text view text if the caculate value between 18 or 25 i used if statment but there is no results
any idea sometimes if i removed one of the >its worked but only for biggest value
public class GB extends ActionBarActivity {
ImageView im1;
EditText mEditText1,mEditText2;
TextView mTextView,m5;
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_GB);
im1 = (ImageView)findViewById(R.id.imageView1);
mEditText1 = (EditText)findViewById(R.id.editText1);
mEditText2 = (EditText)findViewById(R.id.editText2);
mTextView = (TextView)findViewById(R.id.textView4);
m5 = (TextView)findViewById(R.id.textView5);
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
}
String word2 = mEditText2.getText().toString();
String word = mEditText1.getText().toString();
if (word.trim().equals("")){
mEditText1.setError("Insert Hight");
}
else if (word2.trim().equals("")){
mEditText2.setError("Insert Wight");
} else{
calculate();
}
}
});
}
public void calculate(){
Double value1 = Double.parseDouble(mEditText1.getText().toString());
Double value2 = Double.parseDouble(mEditText2.getText().toString());
Double calculatedValue = value1/(value2*value2)*10000;
calculatedValue = Math.round(calculatedValue*10)/10.0d;
mTextView.setText(calculatedValue.toString());
if (mTextView.getText().toString().trim().length() <10 && mTextView.getText().toString().trim().length() >18) {
im1.setBackgroundResource(R.drawable.s1);
m5.setText("low");
} else if (mTextView.getText().toString().trim().length() <18 && mTextView.getText().toString().trim().length() >25) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("Best");
} else if (mTextView.getText().toString().trim().length() <25 && mTextView.getText().toString().trim().length() >100) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("over");
}
}
}
An integer value cannot be smaller than 18 and bigger than 25 at the same time.
Instead of
if (mTextView.getText().toString().trim().length() <18 && mTextView.getText().toString().trim().length() >25)
Use this one if you want to check a value between 18 and 25.
if (mTextView.getText().toString().trim().length() > 18 && mTextView.getText().toString().trim().length() < 25)
If you want to check if a value is in an interval, you have to write it as follows:
if(myvalue > lowerbound && myvalue < upperbound )
The following code probably does what you want.
public void calculate(){
Double value1 = Double.parseDouble(mEditText1.getText().toString());
Double value2 = Double.parseDouble(mEditText2.getText().toString());
Double calculatedValue = value1/(value2*value2)*10000;
calculatedValue = Math.round(calculatedValue*10)/10.0d;
mTextView.setText(calculatedValue.toString());
if (calculatedValue >= 10 && calculatedValue < 18) {
im1.setBackgroundResource(R.drawable.s1);
m5.setText("low");
} else if (calculatedValue >= 18 && calculatedValue < 25) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("Best");
} else if (calculatedValue >= 25 && calculatedValue < 100) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("over");
}
}
Your switch statement here is useless, You have already set click listener to button and again you are trying to check if it's the same button clicked.
It would good if you check if the value entered is numeric.
when you use if, else if and else - one and only one will be executed, which ever full fills the statement will be executed and rest of the code won't execute, say for instance have a look at the following:
if( a > b){
//show A is bigger than b;
} else if ( a == b){
// show A equals to b
} else{
// b > a
}
Here,
if (word.trim().equals("")){//if this conditions works, code won't go to test else if or else statement.
mEditText1.setError("Insert Hight");
}
else if (word2.trim().equals("")){
mEditText2.setError("Insert Wight");
} else{
calculate();
}
The way you are checking the values is wrong, the statement will be always false, as 1. you are testing if the value if < 10 and at the same time you are test if the value is > 18, one of which be false for sure.
if(mTextView.getText().toString().trim().length() <10 && mTextView.getText().toString().trim().length() >18)

Why does it call method 'isCorrect' multiple times (onClick) if I hit the button only once?

I made a simple quiz game for android, right now there's only 10 questions, and 40 answers. (4 answers for each question)
Sometimes when I hit a button it gives me more than one correct answer at a time, also it might even do it when answer's not correct.
Any idea what's wrong in this code? Cause Im not calling the isCorrect boolean method multiple times (in one click).
Code:
public class ETBetaActivity extends Activity implements View.OnClickListener {
Button answer_1,
answer_2,answer_3,
answer_4,main;
TextView q_textview,
tip;
private String a1,a2,a3,a4 = "";
private int i1 = 0;
public static int correct = 0;
private boolean alive = true;
MediaPlayer button_click;
private String[] questions =
{"Q1",
"Q2",
"Q3",
"Q4",
"Q5", //5
"Q6",
"Q7",
"Q8",
"Q9",
"Q10" //10
};
public static int question_amount = 10;
private String[] answers_correct =
{"Correct answer - 1",
"Correct answer - 2",
"Correct answer - 3",
"Correct answer - 4",
"Correct answer - 5",
"Correct answer - 6",
"Correct answer - 7",
"Correct answer - 8",
"Correct answer - 9",
"Correct answer - 10"
};
private String[][] answers_wrong =
{ {"Q1-1", "Q1-2" , "Q1-3"},
{"Q2-1", "Q2-2" , "Q2-3"},
{"Q3-1", "Q3-2" , "Q3-3"},
{"Q4-1", "Q4-2" , "Q4-3"},
{"Q5-1", "Q5-2" , "Q5-3"},
{"Q6-1", "Q6-2" , "Q6-3"},
{"Q7-1", "Q7-2" , "Q7-3"},
{"Q8-1", "Q8-2" , "Q8-3"},
{"Q9-1", "Q9-2" , "Q9-3"},
{"Q10-1", "Q10-2" , "Q10-3"}
};
List<String> question_list = new ArrayList<String>();
List<String> answer_list_correct = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getData();
Game(i1);
}
#Override
public void onClick(View view) {
if (alive == false) {
// startActivity(new Intent("com.aleksei.etb.END"));
return;
}
button_click = MediaPlayer.create(this, R.raw.button_click);
button_click.start();
switch(view.getId()){
case R.id.button5: //main
break;
case R.id.button1: //answer_1
if(isCorrect(1))
correct++;
break;
case R.id.button2: //answer_2
if(isCorrect(2))
correct++;
break;
case R.id.button3: //answer_3
if(isCorrect(3))
correct++;
break;
case R.id.button4: //answer_3
if(isCorrect(4))
correct++;
break;
default:
break;
}
Game(i1);
tip.setText("Correct answers: "+correct);
}
public static int getResults(){
int value = (int) Math.floor((correct*5)/question_amount);
if(value <= 0)
return 1;
else
return value;
}
private boolean isCorrect(int button){
for (int i = 0; i < answers_correct.length; i++){
if(button == 1 && a1 == answers_correct[i]
|| button == 2 && a2 == answers_correct[i]
|| button == 3 && a3 == answers_correct[i]
|| button == 4 && a4 == answers_correct[i])
return true;
}
return false;
}
private void Game(int q){
if(i1 == question_amount) { //no more questions
startActivity(new Intent("com.aleksei.etb.END"));
alive = false;
return;
}
try {
main.setText("Dunno");
String answer_list[] = {
answers_correct[q], answers_wrong[q][0] , answers_wrong[q][1] , answers_wrong[q][2]
};
Collections.shuffle(Arrays.asList(answer_list));
answer_1.setText(answer_list[0]);
answer_2.setText(answer_list[1]);
answer_3.setText(answer_list[2]);
answer_4.setText(answer_list[3]);
a1 = answer_list[0];
a2 = answer_list[1];
a3 = answer_list[2];
a4 = answer_list[3];
q_textview.setText(questions[q]);
} catch (Exception ex){}
i1++;
}
private void getData(){
//Getting the data
main = (Button) findViewById(R.id.button5);
answer_1 = (Button) findViewById(R.id.button1);
answer_2 = (Button) findViewById(R.id.button2);
answer_3 = (Button) findViewById(R.id.button3);
answer_4 = (Button) findViewById(R.id.button4);
q_textview = (TextView) findViewById(R.id.question);
tip = (TextView) findViewById(R.id.answ1);
//Making the buttons, actually work
main.setOnClickListener(this);
answer_1.setOnClickListener(this);
answer_2.setOnClickListener(this);
answer_3.setOnClickListener(this);
answer_4.setOnClickListener(this);
//Resets the text
//Note to self: Replace with another ContectView
main.setText("Begin!");
answer_4.setText("");
answer_3.setText("");
answer_2.setText("");
answer_1.setText("");
tip.setText("");
}
}
Consider the following changes and see if it improves:
private int questionNumber = -1;
private void Game(int q){
...
questionNumber = q;
q_textview.setText(questions[q]);
...
}
private boolean isCorrect(int button){
if(button == 1 && a1.equals(answers_correct[questionNumber])
|| button == 2 && a2.equals(answers_correct[questionNumber])
|| button == 3 && a3.equals(answers_correct[questionNumber])
|| button == 4 && a4.equals(answers_correct[questionNumber]))
return true;
}
return false;
}
Storing the question number as a field eliminates the for loop over all the questions.
You should always use String.equals instead of ==.

Categories