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...
}
}
});
Related
I have this code which is not working:
public class MainActivity extends AppCompatActivity {
int quantity=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i( "MainActivity", "modriodfw" + (R.string.Thankyou));
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
EditText nombre = (EditText) findViewById(R.id.nombre);
String nombre1 = nombre.getText().toString();
boolean cream = getstate();
boolean chocolate = getcState();
int price = calculatePrice(cream, chocolate);
String summary = createOrderSummary(price, cream,chocolate,nombre1);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, (R.string.OrderMail) + nombre1);
intent.putExtra(Intent.EXTRA_TEXT, summary);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(summary);
}
public void clearText(View view)
{
EditText nombre = (EditText) findViewById(R.id.nombre);
nombre.setText("");
}
private boolean getcState()
{
CheckBox state = (CheckBox) findViewById(R.id.chocolate);
boolean chocolateState = state.isChecked();
return chocolateState;
}
private boolean getstate()
{
CheckBox state = (CheckBox) findViewById(R.id.cream);
boolean creamState = state.isChecked();
return (creamState);
}
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = (R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + (R.string.name);
}
if(chocolate && cream == false){
summary += "\n" + quantity + (R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + (R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + (R.string.Thankyou);
return summary;
}
private int calculatePrice(boolean cream, boolean chocolate) {
int price = 5;
if (cream) {
price = price + 1;
}
if (chocolate) {
price = price + 2;
}
price = price * quantity;
return price;
}
public void increase(View view) {
if (quantity == 99){
Toast.makeText(this, (R.string.high), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity + 1;
display(quantity);
}
public void decrease(View view){
if (quantity == 1){
Toast.makeText(this, (R.string.less), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int numb) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText("" + numb);
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String Summary) {
TextView summaryTextView = (TextView) findViewById(R.id.Summary_text_view);
summaryTextView.setText(Summary);
}
and all I get is this:
2131099680
Total: $10
2131099676
and it should be
Name:
summary
total $
Thank You!
im using java in android studio.
You need to do context.getString(R.string.your_string), as R.string.your_string on its own is just a reference.
You have forgotten to call getString method in four places. I update your code :
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = getString(R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + getString(R.string.SummaryChocolate);
}
if(chocolate && cream == false){
summary += "\n" + quantity + getString(R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + getString(R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + getString(R.string.Thankyou);
return summary;
}`enter code here`
This is my Code. When the user enters their answer and press the Submit Button which is the AnswerCheck Method, i would like the score to be shown in a TextView for example - if they input the right answer, the TextView would state 1 correct out of 1. I would like some help, Thanks
public class Perimeter extends AppCompatActivity {
private int number;
private int number2;
private String myString;
private String myString2;
private int perimeter;
private Random rand;
private Random rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
rand = new Random();
rand2 = new Random();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
}
}
Set two global int variables
private int totalQuestion = 0;
and private int correctQuestions = 0;
Inside public void PerimeterGame(View view) increment totalQuestion by one.
When the answer is correct, inside public void AnswerCheck(View view) increment correctQuestion by one.
Finally, display the text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
Hope it helps.
public class Perimeter extends AppCompatActivity {
// Code ommitted
private int totalQuestion = 0 ;
private int correctQuestions = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Code ommitted
}
public void PerimeterGame(View view) {
// Increment totalQuestion
totalQuestion++;
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
correctQuestions++;
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
// Display text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
}
}
i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}
I have an EditText field in my app which is for person's height. How do I format it to make it look like say 5'9"? When a person types 5 the app should add ' by itself and when a person types 9 it should add ". How do I do that? Thank you.
Use this:
public class TextWatcherActivity extends Activity {
EditText e;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e = (EditText) findViewById(R.id.editText1);
e.addTextChangedListener(new CustomTextWatcher(e));
}
}
class CustomTextWatcher implements TextWatcher {
private EditText mEditText;
public CustomTextWatcher(EditText e) {
mEditText = e;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 2) {
return;
} else if (count == 3) {
str = str + "\"";
} else if (count >= 4) {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}
}
Edit:
If user can insert one,two and more digit between ' and " change afterTextChanged in above code like this:
public void afterTextChanged(Editable s) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 3) {
str = str + "\"";
} else if ((count > 4) && (str.charAt(str.length() - 1) != '\"') ){
str = str.substring(0, str.length() - 2) + str.charAt(str.length() - 1)
+ "\"";
} else {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}
use this :
for delete "'".
mBinding.edtHeight.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
if (mBinding.edtHeight.getText().length() == 2) {
mBinding.edtHeight.setText("");
}
}
return false;
}
});
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);
}