I am making a math app. I have two arrays with two sets of numbers. I make the app choose a random number from each array. The app displays that two numbers in a TextView. It asks the user to type in a EditText what the addition of the numbers is. Then when the user presses "Submit", the app will then tell the user if they are right or wrong.
The app works, but I have one main problem. If the user does not type anything in the EditText and presses "Submit", the app force closes. I have looked at other questions asking how to check if a EditText is empty. I tried different methods but it still does not work.
public class MainActivity extends Activity {
Button submitb, startb, idkb;
EditText et;
TextView tv, rig, wron;
int arrone[] = { 24, 54, 78, 96, 48, 65, 32, 45, 95, 13, 41, 55, 33, 22,
71, 5, 22, 17, 13, 29, 63, 72, 14, 81, 7 }; // One Set of Numbers//
int arrtwo[] = { 121, 132, 147, 79, 82, 723, 324, 751, 423, 454, 448,
524, 512, 852, 845, 485, 775, 186, 99 }; // Another set of Numbers//
int random1, random2, add;
int wrong = 0;
int right = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list();
startb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = (int) (Math.random() * 25);
int mun = (int) (Math.random() * 19);
random1 = arrone[num];
random2 = arrtwo[mun];
String yu = (random1 + " + " + random2 + " =");
tv.setText(yu);
et.setHint("");
idkb.setVisibility(0);
startb.setText("Next Question");
}
});
startb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int bread2 = 0;
if (bread2 == 0) {
Toast.makeText(getApplicationContext(),
"You didn't answer the question!",
Toast.LENGTH_LONG).show();
}
int swag = random1 + random2;
String bread = et.getText().toString();
bread2 = Integer.parseInt(bread);
if (bread2 == swag) {
startb.setText("Next Question");
tv.setText("Correct");
et.setText("");
et.setHint("Click Next Question");
right++;
rig.setText("Right:" + right);
rig.setTextColor(Color.parseColor("#14df11"));
bread2 = 0;
}
else if (bread2 == 0) {
tv.setText("Wrong, the correct answer is " + swag + ".");
startb.setText("Next Question");
et.setText("");
tv.setHint("Click Next Question");
wrong++;
wron.setText("Wrong:" + wrong);
wron.setTextColor(Color.parseColor("#ff0000"));
bread2 = 0;
}
else {
tv.setText("Wrong, the correct answer is " + swag + ".");
startb.setText("Next Question");
et.setText("");
et.setHint("Click Next Question");
wrong++;
wron.setText("Wrong:" + wrong);
wron.setTextColor(Color.parseColor("#ff0000"));
bread2 = 0;
}
}
});
idkb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int swag = random1 + random2;
tv.setText("The Correct Answer is " + swag + ".");
et.setText("");
tv.setHint("Click Next Question");
wrong++;
wron.setText("Wrong:" + wrong);
wron.setTextColor(Color.parseColor("#ff0000"));
}
});
}
private void list() {
submitb = (Button) findViewById(R.id.b1);
startb = (Button) findViewById(R.id.b2);
et = (EditText) findViewById(R.id.et1);
tv = (TextView) findViewById(R.id.tv1);
rig = (TextView) findViewById(R.id.rtv);
wron = (TextView) findViewById(R.id.wtv);
idkb = (Button) findViewById(R.id.idk);
}
Few points to consider:
you are setting OnClickListener on startb twice, is it just a typo?
in the second onClick(), you have a condition:
int bread2 = 0;
if (bread2 == 0) {
//rest of code
}
This condition will ALWAYS be satisfied, is that what you want?
you can check if there's nothing entered by use with the following:
String bread = et.getText().toString();
// check if there is any text entered by user
if (bread.length() > 0) {
bread2 = Integer.parseInt(bread);
if (bread2 == swag) {
startb.setText("Next Question");
//the rest of the code
}
Not sure I'm understanding you correctly, but it should be easy as:
et = (EditText) findViewById(R.id.et1);
String bread = et.getText().toString();
if (bread.length() == 0){
// raise error dialogue
} else {
// continue to check the parsed integer
}
This should all be done within your click listener.
You need to use findViewById on the et before gets its value.
By the way, you are setting bread2 value to 0, and on the next line verifying if it's 0, i suppose it's just a test, isn't it?
#Override
public void onClick(View v) {
int bread2 = 0;
if (bread2 == 0) {
Toast.makeText(getApplicationContext(),
"You didn't answer the question!",
Toast.LENGTH_LONG).show();
}
int swag = random1 + random2;
et = findViewById(R.id.yourEditText);
String bread = et.getText().toString();
bread2 = Integer.parseInt(bread);
//...
Hope it helps!
I think it good practice to check text length, for example this function can help you..
public boolean isEditTextEmpty(EditText input){
if(input.getText().length() == 0)
return true;
else
return false;
}
if (et.getText().length == 0 || et.gettext == null ){
// do nothing
} else {
// do whatever here
}
this should works fine
Related
I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});
I have an activity that asks the user a question. Currently it asks questions forever until the user exits the app, but I want it to ask 20 questions, then proceed to a new activity. I thought if I did this:
for(int i = 0;i < 20;i++){
random = new Random();
chooseQuestion();
}
Intent i = new Intent(PlayGame.this, Gamble.class);
startActivity(i);
it would work, but my app is now breaking. Am I opening a new activity incorrectly, and if so how should I proceed?
Ok I'm really new to this and I don't know how much of the code to post in response to a comment so here's all of it, I'm sorry.
public class PlayGame extends Activity implements OnClickListener {
//set up minimum and maximum numbers for different operators and difficulty levels
private int level = 0, answer = 0, operator = 0, operand1 = 0, operand2 = 0;
private final int ADD_OPERATOR = 0, SUBTRACT_OPERATOR = 1, MULTIPLY_OPERATOR = 2, DIVIDE_OPERATOR = 3;
private String[] operators = {"+", "-", "x", "/"};
private int[][] levelMin = {
{1, 11, 21},
{1, 5, 10},
{2, 5, 10},
{2, 3, 5}};
private int[][] levelMax = {
{10, 25, 50},
{10, 20, 30},
{5, 10, 15},
{10, 50, 100}};
private Random random;
private TextView question, answerTxt, scoreTxt, coincountTxt;
private ImageView response;
private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, enterBtn, clearBtn;
#Override
//tell the buttons to be buttons when the activity is opened
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
coincountTxt = (TextView)findViewById(R.id.coincount);
response.setVisibility(View.INVISIBLE);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
}
for(int i = 0;i < 20;i++){
random = new Random();
chooseQuestion();
}
Intent i = new Intent(PlayGame.this, Gamble.class);
startActivity(i);
}
//find which button pressed on main menu and set operator accordingly
public int getOperator() {
Bundle extras = getIntent().getExtras();
int type = extras.getInt("type", -1);
if(type==1) operator = ADD_OPERATOR;
else if(type==2) operator = SUBTRACT_OPERATOR;
else if(type==3) operator = MULTIPLY_OPERATOR;
else if(type==4) operator = DIVIDE_OPERATOR;
//randomly finds operator for each successive question
else if(type==5) operator = random.nextInt(operators.length);
return operator;
}
//get random valid question within the parameters defined by operation and difficulty
private void chooseQuestion(){
//get a question
answerTxt.setText("= ?");
operator = getOperator();
operand1 = getOperand();
operand2 = getOperand();
//get new subtraction question if answer is negative
if(operator == SUBTRACT_OPERATOR){
while(operand2>operand1){
operand1 = getOperand();
operand2 = getOperand();
}
}
//get new division question if answer is not whole number
else if(operator==DIVIDE_OPERATOR){
while((((double)operand1/(double)operand2)%1 > 0) || (operand1==operand2))
{
operand1 = getOperand();
operand2 = getOperand();
}
}
//find answer to question
switch(operator)
{
case ADD_OPERATOR:
answer = operand1+operand2;
break;
case SUBTRACT_OPERATOR:
answer = operand1-operand2;
break;
case MULTIPLY_OPERATOR:
answer = operand1*operand2;
break;
case DIVIDE_OPERATOR:
answer = operand1/operand2;
break;
default:
break;
}
//set text to show question on screen
question.setText(operand1+" "+operators[operator]+" "+operand2);
}
//random number generator
private int getOperand(){
//return operand number
return random.nextInt(levelMax[operator][level] - levelMin[operator][level] + 1)
+ levelMin[operator][level];
}
//tell buttons what to do when clicked on
#Override
public void onClick(View view) {
//button clicked
if(view.getId()==R.id.enter){
//enter button
String answerContent = answerTxt.getText().toString();
if(!answerContent.endsWith("?"))
{
//answer has been entered, check if correct
int enteredAnswer = Integer.parseInt(answerContent.substring(2));
int exScore = getScore();
int exCoincount = getCoincount();
if(enteredAnswer==answer){
//correct - show tick and add one to score and coincount
scoreTxt.setText("Score: "+(exScore+1));
response.setImageResource(R.drawable.tick);
response.setVisibility(View.VISIBLE);
coincountTxt.setText(""+(exCoincount+1));
}
else{
//incorrect - show cross and reset score to 0
scoreTxt.setText("Score: 0");
response.setImageResource(R.drawable.cross);
response.setVisibility(View.VISIBLE);
}
//show new question
chooseQuestion();
}
}
//if clear button clicked reset answer text to question mark
else if(view.getId()==R.id.clear){
//clear button
answerTxt.setText("= ?");
}
else if(view.getId()==R.id.help_btn){
//help button
Intent i = new Intent(PlayGame.this, HowToPlay.class);
startActivity(i);
}
//if number clicked:
else {
//number button
response.setVisibility(View.INVISIBLE);
int enteredNum = Integer.parseInt(view.getTag().toString());
//if first number replace question mark
if(answerTxt.getText().toString().endsWith("?"))
answerTxt.setText("= "+enteredNum);
//if subsequent number append to previous
else
answerTxt.append(""+enteredNum);
}
}
//function to calculate score (used above in 'correct' if statement
private int getScore(){
String scoreStr = scoreTxt.getText().toString();
return Integer.parseInt(scoreStr.substring(scoreStr.lastIndexOf(" ")+1));
}
//function to calculate number of coins
private int getCoincount(){
String coincountStr = coincountTxt.getText().toString();
return Integer.parseInt(coincountStr.substring(coincountStr.lastIndexOf(" ")+1));
}
}
The code I was referencing is onCreate() and it calls the function chooseQuestion() from not far below that.
Use a Handler
new Handler().postDelayed(new Runnable(){
public void run(){
//start activity here
}
}, 1000);
Try this:
for(int i = 0;i <= 20;i++){
if(i==20){
Intent i = new Intent(PlayGame.this, Gamble.class);
startActivity(i);
break;
} else {
random = new Random();
chooseQuestion();
}
}
Use a Thread
new Thread(new Runnable() {
#Override
public void run() {
//enter code here
}).start();}
I am trying to make an Simple MCQ app with the use of multidimension string array.
here is my code for MainActivity:
My question is how can I define array of answers. I done addition but it won't work.
public class MainActivity extends Activity {
RadioGroup radioGroup;
RadioButton rb1, rb2, rb3, rb4;
TextView tvquestion, tvtotallength_yy, tvpresentindex_xx;
Button previous, answer, next, result;
int q, a, wrong, count;
String[][] array = {{"Question 1", "Question 2", "Question 3", "Question 4", "Question 5", "Question 6", "Question 7", "Question 8", "Question 9", "Question 10"},
{
"1answerA", "1answerB", "1answerC", "1answerD",
"2answerA", "2answerB", "2answerC", "2answerD",
"3answerA", "3answerB", "3answerC", "3answerD",
"4answerA", "4answerB", "4answerC", "4answerD",
"5answerA", "5answerB", "5answerC", "5answerD",
"6answerA", "6answerB", "6answerC", "6answerD",
"7answerA", "7answerB", "7answerC", "7answerD",
"8answerA", "8answerB", "8answerC", "8answerD",
"9answerA", "9answerB", "9answerC", "9answerD",
"10answerA", "10answerB", "10answerC", "10answerD",
}
};
String[] ans = {"1answerA", "2answerD", "3answerC", "4answerA", "5answerB", "6answerB", "7answerA", "8answerC", "9answerD", "10answerD"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialing text view
tvquestion = (TextView) findViewById(R.id.tvquestion);
tvtotallength_yy = (TextView) findViewById(R.id.tvyy);
tvpresentindex_xx = (TextView) findViewById(R.id.tvxx);
//initializing button
previous = (Button) findViewById(R.id.previous);
answer = (Button) findViewById(R.id.answer);
next = (Button) findViewById(R.id.next);
result = (Button) findViewById(R.id.result);
//initializing radio button
radioGroup = (RadioGroup) findViewById(R.id.radiogrp);
rb1 = (RadioButton) findViewById(R.id.optionA);
rb2 = (RadioButton) findViewById(R.id.optionB);
rb3 = (RadioButton) findViewById(R.id.optionC);
rb4 = (RadioButton) findViewById(R.id.optionD);
count = 0;
wrong = 0;
q = 0;
a = 0;
tvquestion.setText(array[0][q]);
rb1.setText(array[1][q]);
rb2.setText(array[1][q+1]);
rb3.setText(array[1][q+2]);
rb4.setText(array[1][q+3]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
//setting the button to perform specific action
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
q--;
if (q == -1) {
q = array.length - 1;
tvquestion.setText(array[0][q]);
rb1.setText(array[1][q]);
rb2.setText(array[1][q + 4]);
rb3.setText(array[1][q + 8]);
rb4.setText(array[1][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
} else {
tvquestion.setText(array[0][q]);
rb1.setText(array[1][a]);
rb2.setText(array[1][q + 4]);
rb3.setText(array[1][q + 8]);
rb4.setText(array[1][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
}
}
});
answer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.optionA:
if (ans[q] == array[1][q]) {
count++;
} else {
wrong++;
}
break;
case R.id.optionB:
if (ans[q] == array[1][q + 4]) {
} else {
wrong++;
}
break;
case R.id.optionC:
if (ans[q] == array[1][q + 8]) {
} else {
wrong++;
}
break;
case R.id.optionD:
if (ans[q] == array[1][q + 12]) {
} else {
wrong++;
}
break;
}
}
});
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioGroup.clearCheck();
q++;
if (q == array.length) {
q = 0;
tvquestion.setText(array[0][q]);
rb1.setText(array[0][q]);
rb2.setText(array[0][q + 4]);
rb3.setText(array[0][q + 8]);
rb4.setText(array[0][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
} else {
tvquestion.setText(array[0][q]);
rb1.setText(array[1][q]);
rb2.setText(array[1][q + 4]);
rb3.setText(array[1][q + 8]);
rb4.setText(array[1][q + 12]);
tvpresentindex_xx.setText(String.valueOf(q + 1));
}
}
});
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Correct=" + count + " Incorrect=" + wrong, Toast.LENGTH_LONG).show();
}
});
}
}
Instead of storing the actual answer
String[] ans = {"1answerA", "2answerD", "3answerC", "4answerA", "5answerB", "6answerB", "7answerA", "8answerC", "9answerD", "10answerD"};
you can store the index of the answer like this. Suppose you have 10 question and 4 choices which you are storing in an array. So you can define an int array of answers like this
int[] answers_index = new int[]{1,2,2,3,1,1,3,3,1,4,4};
You can try storing the index of the answers as an integer array. For example, if your answers are a,d,c and b respectively for 4 questions, your answer array can be
[0,3,2,1]. Then number the radio buttons so that button 1 has is represented by 0 and so on. Finally, when the user enters an answer, you can compare the number representation of the button to the integer value in your answer array to check for correctness.
Hope this helps!
The program draws two digits, and the sign. IF statement checks to see if it has been drawn + / -. If it draws + add, if - is subtraction.
Draw works.
Then the user is given the result of the task. And here is the problem.
If you give a result which is in the "result". Function if something does. If you entered an incorrect answer is displayed Toast: Try Again.
The problem is that sometimes as to give a good result is is displayed Try Again.
How to eliminate this problem? Might different check?
Code:
private String sign;
private int numberOne, numberTwo, result = 0;
private int charsEntered = 0;
private EditText et;
private Button ok;
String[] CHAR = { "+", "-" };
Random intGen = new Random();
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
mCorrectListener = listener;
}
public EasyMathCaptcha(Context context) {
super(context);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static int randomOne() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public static int randomTwo() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.all_math_captcha);
sign = (CHAR[Math.abs(intGen.nextInt() % 2)]);
numberOne = randomOne();
numberTwo = randomTwo();
TextView display = (TextView) findViewById(R.id.tvRandomTask);
display.setText(numberOne + " " + sign + " " + numberTwo);
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
et = (EditText) findViewById(R.id.etTask);
ok = (Button) findViewById(R.id.btAgree);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = Integer.parseInt(et.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "That's not a number!",
Toast.LENGTH_SHORT).show();
}
if (charsEntered == result) {
if (mCorrectListener != null)
mCorrectListener.onCorrect();
dismiss();
} else if (charsEntered != result) {
Toast.makeText(et.getContext(), "Try again!", Toast.LENGTH_SHORT)
.show();
}
}
}
The error is in the following code:
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
You are using the random number generator which can give you results different than what it gave the first time.
Change it to:
if (sign.equals("+")) {
result = (numberOne + numberTwo);
} else if (sign.equals("-")) {
result = (numberOne - numberTwo);
}