Factorial program in android - android

Hey guys I know there are many java programs for the factorial of a number...but I am facing problem with android. Following is my code....Thanks
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
long factorial = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
calcFactorial();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private void calcFactorial() {
if (number.getText().toString().equals("")) number.setText("0");
int num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
#Override
public void onClick(View v) {
calcFactorial();
answer.setText("Factorial of " + number.getText().toString() + " is : " + factorial);
}
}
This is my code and I need to know a way around for setting the hint instead of 0, but if I remove if (number.getText().toString().equals("")) number.setText("0");
then getting NullPointerException...
Also on the first go its calculating correctly but If I calculate again then getting wrong answer. I think some loop issue because I am directly using the value of factorial.
Please help thanks

Forget all that equal stuff, cover all basis and do it like this:
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P")
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private long calcFactorial() {
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}
return factorial;
}
#Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " + calcFactorial());
}

Do something like.
private void calcFactorial() {
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}

Rather than using
(number.getText().toString().equals("")) number.setText("0");
Use
(number.getText().length==0) number.setText("0");

** first go its calculating correctly but If I calculate again then getting wrong answer**
try like this
private void calcFactorial() {
factorial = 1;///Check out the line..
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
You need to make sure variable factorial is reinitialise to 1 .. for getting factorial for next number..

private void fact_isClicked(View view) {
if(textField.length()>0){
int ifac = Integer.parseInt(textField.getText().toString());
int fact = factorial(ifac);
tvsec.setText(String.valueOf(fact));
textField.setText(ifac+"!");
}}

Related

How can i randomize question in a quiz app

I made a simple quiz on Android Studio which contains 3+ questions. How to make the questions become random without duplicated. This app does not use a database. I'm new to programming so I don't know what to do about this
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView;
TextView questionTextView;
Button ansA,ansB,ansC,ansD;
Button submitBtn;
int score=0;
int totalQuestions = QuestionAnswer.question.length;
int currentQuestionIndex = 0;
String selectedAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalQuestionsTextView = findViewById(R.id.total_questions);
questionTextView = findViewById(R.id.question);
ansA = findViewById(R.id.ans_A);
ansB = findViewById(R.id.ans_B);
ansC = findViewById(R.id.ans_C);
ansD = findViewById(R.id.ans_D);
submitBtn = findViewById(R.id.submbit_btn);
ansA.setOnClickListener(this);
ansB.setOnClickListener(this);
ansC.setOnClickListener(this);
ansD.setOnClickListener(this);
submitBtn.setOnClickListener(this);
totalQuestionsTextView.setText("Total Questions : "+totalQuestions);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA.setBackgroundColor(Color.WHITE);
ansB.setBackgroundColor(Color.WHITE);
ansC.setBackgroundColor(Color.WHITE);
ansD.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submbit_btn){
currentQuestionIndex++;
loadNewQuestion();
}else{
//choices button clicked
selectedAnswer = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex == totalQuestions){
finishQuiz();
return;
}
questionTextView.setText(QuestionAnswer.question[currentQuestionIndex]);
ansA.setText(QuestionAnswer.choices[currentQuestionIndex][0]);
ansB.setText(QuestionAnswer.choices[currentQuestionIndex][1]);
ansC.setText(QuestionAnswer.choices[currentQuestionIndex][2]);
ansD.setText(QuestionAnswer.choices[currentQuestionIndex][3]);
}
void finishQuiz(){
String passStatus = "";
if (score > totalQuestions*0.60){
passStatus = "Passes";
}else{
passStatus = "Failed";
}
new AlertDialog.Builder(this)
.setTitle(passStatus)
.setMessage("Score is "+score+" out of "+ totalQuestions)
.setPositiveButton("Restart",(dialogInterface, i) -> restartQuiz())
.setCancelable(false)
.show();
}
void restartQuiz(){
score = 0;
currentQuestionIndex = 0;
loadNewQuestion();
}
QuestionAnswer.java
import java.util.Arrays; import java.util.List; import java.util.Random;
public class QuestionAnswer {
public static String[] question = {
"Which company own the android?",
"Which one is not the programming language?",
"Where are you watching this video"
};
public static String choices[][] = {
{"Google", "Apple", "Nokia", "Samsung"},
{"Java", "Kotlin", "Notepad", "Python"},
{"Facebook", "Whatsapp", "Instagram", "Youtube"},
};
public static String correctAnswers[] = {
"Google",
"Notepad",
"Youtube"
};
}
how can i add shuffle.collection or random to make my app show random question instead
You need to find out about Random class first in Java. Thereafter, you will create a random number using Random class in onClick function, then set a question's index to your Random number

Closing Android Game After 5 Seconds

I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}

Android calculator: button for decimal place

I am new to Android development and currently learning to design for a basic calculator app. I have already self designed the layout, but sourced Main Activity codes from different websites for the operations for 0 to 9, +, -, *, / and after incorporation, they work fine.
However, I do want to further modify the MainActivity with decimal point function.
While integer can be shown properly to the screen using "current = current * 10 + number", eg 53 = 5*10+3;
I am thinking applying the same approach for decimal point with a loop function, the idea like this:
1. current = current + remaining if dot button is pressed
2. create an integer i, i increases by 1 once any numerial button is clicked
3. so that when e.g. input 5.3, i =1, it will = 5 + 3/(10^i) = 5.3
4. 5.3 loop to here, then when e.g. input as 5.39, now i=2, it will = 5.3 + 9/(10^i) = 5.39
QUESTION >>
*Yet...really...I am so fresh that I do not know how to design the coding for the decimal button, would there be anyone can suggest the code?* first ignore the following addons where errors to be detected (such as delete the second dot if the dot is input twice or more, adding 0 in front of . if say, .5 is input)
The button id is as follows, and once clicked to refer to DecimalClickEvent
Button b_decimal = (Button) findViewById(R.id.decimal);
b_decimal.setOnClickListener(new DecimalClickEvent(???));}
Many many thanks in advance!! The codes are attached below for reference and your comments:
=========================MainActivity.java=====================================
package com.trial.newcalculator;
import java.io.Serializable;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
#SuppressLint("ParserError")
public class MainActivity extends Activity {
State s;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s = new State();
int[] opNumbers = new int[] {
R.id.zero,
R.id.one,
R.id.two,
R.id.three,
R.id.four,
R.id.five,
R.id.six,
R.id.seven,
R.id.eight,
R.id.nine,
};
final TextView textView = (TextView) findViewById(R.id.ansEditText);
for (int i = 0; i < 10;i++){
final Button button = (Button) findViewById(opNumbers[i]);
button.setOnClickListener(new NumberClickEvent(textView,s,i));
}
int[] opButtons = new int[] { R.id.add, R.id.subtract, R.id.multiply, R.id.divide };
State.Operation[] states = new State.Operation[] {
State.Operation.PLUS,
State.Operation.MINUS,
State.Operation.MULTIPLY,
State.Operation.DIVIDE};
for(int i = 0; i < opButtons.length;i++){
Button b_op = (Button) findViewById(opButtons[i]);
b_op.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
}
// Memory functions
int[] memButtons = new int[] { R.id.MC, R.id.MR, R.id.Mdeduct, R.id.Mplus};
State.Operation[] mstates = new State.Operation[] {
State.Operation.MEMORYCLEAR,
State.Operation.MEMORYCALL,
State.Operation.MEMORYMINUS,
State.Operation.MEMORYPLUS};
for(int i = 0; i < memButtons.length;i++){
Button b_mem = (Button) findViewById(memButtons[i]);
b_mem.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
}
// Memory functions
//decimal
// Button b_decimal = (Button) findViewById(R.id.decimal);
// b_decimal.setOnClickListener(new DecimalClickEvent(textView, s, "."));
//decimal
Button b_eq = (Button) findViewById(R.id.equal);
b_eq.setOnClickListener(new EqualClickEvent(textView, s));
Button b_op = (Button) findViewById(R.id.ac);
b_op.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
s.clear();
textView.setText(s.getDisplay());
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("STATE", s);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Serializable serializable = savedInstanceState.getSerializable("STATE");
if(serializable!= null){
s = (State) serializable;
}
}
public void onPause(){
super.onPause();
}
}
===============================State.java==================================
package com.trial.newcalculator;
import java.io.Serializable;
import android.text.Editable;
import android.widget.TextView;
public class State implements Serializable {
private static final long serialVersionUID = -1231231231231233L;
public TextView output;
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
MEMORYPLUS,
MEMORYMINUS,
MEMORYCALL,
MEMORYCLEAR,
}
public enum IOState{
INPUTTING,
DISPLAY_RESULT,
}
private Double accu = null;
private double current = 0;
private double memory = 0;
private Operation currentOp = null;
private IOState currentState = IOState.INPUTTING;
public Operation getCurrentOp() {
return currentOp;
}
public void setCurrentOp(Operation currentOp) {
if (currentState == IOState.INPUTTING){
if (accu != null && this.currentOp != null ){calculateResult();
}
else{accu = Double.valueOf(current);current = 0;
}
}
this.currentOp = currentOp;
if (currentState == IOState.INPUTTING){
currentState = IOState.DISPLAY_RESULT;
}
}
private void calculateResult() {
double res = accu.doubleValue();
switch (currentOp) {
case PLUS:
res += current;
break;
case MINUS:
res -= current;
break;
case MULTIPLY:
res *= current;
break;
case DIVIDE:
res /= current;
break;
case MEMORYPLUS:
memory += current;
break;
case MEMORYMINUS:
memory -= current;
break;
case MEMORYCLEAR:
memory = 0;
break;
case MEMORYCALL:
current = memory;
break;
}
accu = Double.valueOf(res);
current = 0;
}
public void number(int number) {
if (currentState == IOState.INPUTTING){
current = current *10 + number;
}
else if(currentState == IOState.DISPLAY_RESULT){
currentState = IOState.INPUTTING;
current = number;
}
}
public String getDisplay() {
String res;
Double d = getCurrentDisplayValue();
double doubleValue = d.doubleValue();
int intVal = (int)doubleValue;
if (intVal == doubleValue){
res = Integer.toString(intVal);
}
else{
res = d.toString();
}
return res;
}
private Double getCurrentDisplayValue() {
Double d = accu;
if (currentState == IOState.INPUTTING){
d = Double.valueOf(current);
}
return d;
}
public void clear() {
accu = null;
currentState = IOState.INPUTTING;
currentOp = null;
current = 0;
}
public void equal() {
if (accu == null || currentOp == null){
return;
}
calculateResult();
currentState = IOState.DISPLAY_RESULT;
currentOp = null;
current = getCurrentDisplayValue();
}
}
====================OperationClickEvent.java===============================
package com.trial.newcalculator;
import com.trial.newcalculator.State.Operation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class OperationClickEvent implements OnClickListener {
private State s;
private TextView textView;
private Operation op;
public OperationClickEvent(TextView textView, State s, State.Operation op) {
super();
this.op = op;
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.setCurrentOp(op);
textView.setText(s.getDisplay());
}
}
=================EqualClickEvent.java=======================================
package com.trial.newcalculator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class EqualClickEvent implements OnClickListener {
private State s;
private TextView textView;
public EqualClickEvent(TextView textView, State s) {
super();
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.equal();
textView.setText(s.getDisplay());
}
}
======================NumberClickEvent.java==================================
package com.trial.newcalculator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class NumberClickEvent implements OnClickListener {
private int number;
private State s;
private TextView textView;
public NumberClickEvent(TextView textView, State s, int number) {
super();
this.number = number;
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.number(number);
textView.setText(s.getDisplay());
}
}
Instead of creating new classes for negative click event and doublezeroclickevent, i suggest you to get their id's and do the proper functionality when the particular button is clicked .
Each OnClickListener can be a default anonymous class, that will be triggered only by one button.
So no need to name them "NegativeClickEvent", "DoublezeroClickEvent", etc.
You can keep a boolean variable if the "." was pressed, and accept another one only if not.
If you want a usable calculator, you need a "backspace" button as well. So note that the dot may be deleted. (need to keep track of its placement).
For the leading 0, you can use a simple "if dot was pressed first, insert 0.".
There are many ways to implement what you want, but to keep it simple, just handle the cases you need to handle.
Other ways to implement this may include Double.parseDouble(s) with catch (NumberFormatException e) on each key pressed, or using a double as your buffer, and using the buttons to perform mathematical operations on it directly (such as multiply by 10 and adding the new digit on each button press) - this will ensure input validity without the need to parse String, but it's more complicated to implement.

Getting zero as result (android)

I am getting zero as the output. I couldnt find any errors in it
any help would be great.
full code:
package com.equbez.resistor_decoder;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Second extends Activity {
int i,b1,b2,b3,result,four;
String one,two,three;
String arr[]={"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
EditText etone=(EditText) findViewById(R.id.editText1);
one=etone.getText().toString();
for(i=0;i<9;i++) {
if(one.equalsIgnoreCase(arr[i])) {
b1=i;
}
}
EditText ettwo=(EditText) findViewById(R.id.editText2);
two=ettwo.getText().toString();
for(i=0;i<9;i++) {
if(two.equalsIgnoreCase(arr[i])) {
b2=i;
}
}
EditText etthree=(EditText) findViewById(R.id.editText3);
three=etthree.getText().toString();
for(i=0;i<9;i++) {
if(three.equalsIgnoreCase(arr[i])) {
b3=i;
}
}
result=b2+b2+b3;
Button bfour=(Button) findViewById(R.id.button4);
bfour.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View V) {
TextView tv=(TextView) findViewById(R.id.textView4);
tv.setText(""+result);
}
});
}
}
any help would be great.
initially the EditTextView will be empty when the activity is called. so you always get an empty string which you are comparing to the Strings in arr[].
b1, b2, b3 are initialized to default values ie.,, '0' hence result is always '0'
write all the getText code in the bfour.setOnClickListener()
or else implement TextWatcher and use onTextChanged method
use
for(i = 0 ; i< arr.length ;i++)
do something
In your code if you are inputting white its not getting compared
Are you giving any spaces while inputing the string at the end? once check the length of the string that you give as input whether its exact or not
Here i have re-coded with the changes, try out this code,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Second extends Activity
{
private static int b1,b2,b3,result,four;
private String one,two,three;
private String arr[]={"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
EditText etone=(EditText) findViewById(R.id.editText1);
one=etone.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(one.trim().equalsIgnoreCase(arr[i].trim()))
{
b1=i;
break;
}
}
EditText ettwo=(EditText) findViewById(R.id.editText2);
two=ettwo.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(two.trim().equalsIgnoreCase(arr[i].trim()))
{
b2=i;
break;
}
}
EditText etthree=(EditText) findViewById(R.id.editText3);
three=etthree.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(three.trim().equalsIgnoreCase(arr[i].trim()))
{
b3=i;
break;
}
}
result=b2+b2+b3;
Button bfour=(Button) findViewById(R.id.button4);
bfour.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View V)
{
TextView tv=(TextView) findViewById(R.id.textView4);
tv.setText( String.valueOf(result));
}
});
}
}
I got the problem. You have to run your all 3 loops after clicking the button. you have done that on Oncreate(). So you always get 0.
see below:
int i, b1, b2, b3, result, four;
String one, two, three;
String arr[] = { "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" };
EditText etone, ettwo, etthree;
Button bfour;
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
etone = (EditText) findViewById(R.id.editText1);
ettwo = (EditText) findViewById(R.id.editText2);
etthree = (EditText) findViewById(R.id.editText3);
bfour = (Button) findViewById(R.id.button4);
bfour.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
one = etone.getText().toString();
for (i = 0; i < arr.length; i++) {
if (one.equals(arr[i])) {
b1 = i;
System.out.println("dhrupal one="+b1);
}
}
two = ettwo.getText().toString();
for (i = 0; i < arr.length; i++) {
if (two.equals(arr[i])) {
System.out.println("dhrupal one="+two);
b2 = i;
}
}
three = etthree.getText().toString();
for (i = 0; i < arr.length; i++) {
if (three.equals(arr[i])) {
System.out.println("dhrupal one="+three);
b3 = i;
}
}
result = b1 + b2 + b3;
tv = (TextView) findViewById(R.id.textView4);
tv.setText("result=" + result);
}
});
}

What is wrong with my android simple calculator app?

I'm new to android and this is my first application, it seems fine to me but every time I pressed the calculate button it seems to stop unexpectedly and force close.
package com.test.simplecalc;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button myButton = (Button) findViewById(R.id.myButton);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secondNum = (EditText)findViewById(R.id.secondNum);
final EditText finalNum = (EditText)findViewById(R.id.finalNum);
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int num1 = 0;
try {
num1 = Integer.parseInt(firstNum.getText().toString());
} catch(NumberFormatException nfe) {
Toast.makeText(MainActivity.this, "Could not parse" + nfe, Toast.LENGTH_SHORT).show();
}
int num2 = 0;
try {
num2 = Integer.parseInt(secondNum.getText().toString());
} catch(NumberFormatException nfe) {
Toast.makeText(MainActivity.this, "Could not parse" + nfe, Toast.LENGTH_SHORT).show();
}
int num3 = num1 + num2;
finalNum.setText(num3);
}
});
}
}
It's likely that one of the two blocks is throwing something other than NumberFormatException. (My guess would be a NullPointerException in the call to toString().)
Try changing the caught exception in each case to Exception and see if this reveals the problem.
just try
num3.toString()
while printing the answer, and better to use textview for showing answer

Categories

Resources