2

I am building a simple calculator, but for some reason, it crashes as soon as I press a button. Please help me out with it.

This is my Calculator.java class.

package com.dexter.seemab;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class Calculator extends Activity{   
String display="";
 Character op = 'q';
 int i,num,numtemp;
 int check=0;
 EditText rd;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calculator);
    rd=(EditText)findViewById(R.id.etResult);


}
public void btnClicked(View v){
    switch(v.getId()){
    case R.id.one:{
        insert(1);
    }
    case R.id.two:{
        insert(2);
    }
    case R.id.three:{
        insert(3);
    }
    case R.id.four:{
        insert(4);
    }
    case R.id.five:{
        insert(5);
    }
    case R.id.six:{
        insert(6);
    }
    case R.id.seven:{
        insert(7);
    }
    case R.id.eight:{
        insert(8);
    }
    case R.id.nine:{
        insert(9);
    }
    case R.id.zero:{
        insert(0);
    }
    case R.id.add:{
        perform();
        op='+';
    }
    case R.id.sub:{
        perform();
        op='-';
    }
    case R.id.product:{
        perform();
        op='*';
    }
    case R.id.difference:{
        perform();
        op='/';
    }
    case R.id.equals:{
        calculate();
    }
    case R.id.clear:{
        clear();
    }
    }
}
public void insert(int digit){
    if (check==1){
        clear();}
    display=display+Integer.toString(digit);
    num=Integer.valueOf(display).intValue();
    rd.setText(display);
    check=0;
}
public void perform(){
    numtemp=num;
    display=display+op.toString();
}
public void calculate(){
    switch(op){
    case '+':
        i=num+numtemp;
    case '-':
        i=num-numtemp;
    case '*':
        i=num*numtemp;
    case '/':
        i=num/numtemp;
    }
    display=Integer.toString(i);
    rd.setText("="+display);
    check=1;
}
public void clear(){
    op='q';
    num=0;
    numtemp=0;
    i=0;
    display="";
    rd.setText(display);
}

}

my buttons contain an onClick listener which points to the method btnClicked(). Now whenever I press a button, the program of mine crashes. PLease help me out with it. Thanks.

Seemab Hassan
  • 63
  • 1
  • 10
  • you have not defined any button in your activity class. – DroidDev Feb 05 '14 at 12:19
  • Exactly where you get the error and post your log-cat details. – Yugesh Feb 05 '14 at 12:19
  • my buttons contain an onClick listener which points to the method btnClicked().-----where are the buttons and click listeners, what error is thrown before your program crashes, to help you, everybody must know that – Pararth Feb 05 '14 at 12:21
  • @user2450263, @VishwasSharma obviously the SO refers to the `onClick` attribute in the xml buttons set to `btnClicked`, here. – njzk2 Feb 05 '14 at 14:05
  • You don't have any breaks in your case... – njzk2 Feb 05 '14 at 14:06
  • In all your cases, use a 'break' or it will continue an all others cases – Tsunaze Feb 05 '14 at 15:24

3 Answers3

0

first change num=Integer.valueOf(display).intValue();

TO

num=Integer.parse(display);

and change display=Integer.toString(i);

TO

display=String.valueOf(i);
Mohammad Rababah
  • 1,730
  • 4
  • 17
  • 32
0

There are some things that should cause your App to crash:

As you do not use break-statements at the end of your cases, every case from the one matching your button-id to the last statement (R.id.clear) will be executed. This certainly is unexpected behaviour that you should fix.

Further num / numtemp is wrong as numtemp represents the firstly entered number and num the last number.

This is your fixed code. Read below what caused the Exception:

package com.dexter.seemab;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class Calculator extends Activity {
    String display = "";
    Character op = 'q';
    int i, num, numtemp;
    int check = 0;
    EditText rd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculator);
        rd = (EditText) findViewById(R.id.etResult);

    }

    public void btnClicked(View v) {
        switch (v.getId()) {
        case R.id.one:
            insert(1);
            break;
        case R.id.two:
            insert(2);
            break;
        case R.id.three:
            insert(3);
            break;
        case R.id.four:
            insert(4);
            break;
        case R.id.five:
            insert(5);
            break;
        case R.id.six:
            insert(6);
            break;
        case R.id.seven:
            insert(7);
            break;
        case R.id.eight:
            insert(8);
            break;
        case R.id.nine:
            insert(9);
            break;
        case R.id.zero:
            insert(0);
            break;
        case R.id.add:
            op = '+';
            perform();
            break;
        case R.id.sub:
            op = '-';
            perform();
            break;
        case R.id.product:
            op = '*';
            perform();
            break;
        case R.id.difference:
            op = '/';
            perform();
            break;
        case R.id.equals:
            calculate();
            break;
        case R.id.clear:
            clear();
            break;
        }
    }

    public void insert(int digit) {
        if (check == 1) {
            clear();
        }
        display = display + Integer.toString(digit);
        if(op == 'q') {
            num = Integer.valueOf(display).intValue();
        } else {
            String[] digits = display.split("\\"+op.toString());
            num = Integer.valueOf(digits[digits.length-1]);
        }
        rd.setText(display);
        check = 0;
    }

    public void perform() {
        numtemp = num;
        display = display + op.toString();
    }

    public void calculate() {
        switch (op) {
        case '+':
            i = numtemp + num;
            break;
        case '-':
            i = numtemp - num;
            break;
        case '*':
            i = numtemp * num;
            break;
        case '/':
            i = numtemp / num;
            break;
        }
        display = Integer.toString(i);
        rd.setText("=" + display);
        check = 1;
    }

    public void clear() {
        op = 'q';
        num = 0;
        numtemp = 0;
        i = 0;
        display = "";
        rd.setText(display);
    }

}

Another hint: You're calculator is not able to perform simple tasks like 3+4-5. If you want those terms to be calculated you have to change at least the perform()-method.

EDIT:

I found the cause of the crash: It is an NumberFormatException thrown in this line: num = Integer.valueOf(display).intValue();. It occurs (with my corrected code) when you click the first digit after the operator. It occurs because something like 12+8 cannot be parsed to int. So you have two choices to fix this:

1) In method perform: Change display = display + op.toString(); to display = "";. This will fix the Exception, but it is not very user-friendly.

2) In method insert: Change num = Integer.valueOf(display).intValue(); to

if(op == 'q') {
    num = Integer.valueOf(display).intValue();
} else {
    String[] digits = display.split("\\"+op.toString());
    num = Integer.valueOf(digits[digits.length-1]);
}

This way your EditText will display text like "12+52" which is more user-friendly.

chuky
  • 1,037
  • 1
  • 12
  • 21
  • I did it the same way u said. but still not working. application crashes. – Seemab Hassan Feb 06 '14 at 22:54
  • With what Exception does it crash? – chuky Feb 07 '14 at 06:12
  • how do I see the exception? – Seemab Hassan Feb 07 '14 at 09:07
  • It's in the stacktrace in your LogCat. If you use eclipse you can open it as follows: Window->Show View->Other->LogCat->OK – chuky Feb 07 '14 at 09:10
  • thanks for the help. I was able to identify the problem with the help of logcat. I was doing mistake in xml file, onclick method was not properly being invoked. thanks again for your help. – Seemab Hassan Feb 07 '14 at 09:42
  • No problem! I'd be happy if you accept my answer if you feel like my help guided you through some other errors in your code ;) – chuky Feb 07 '14 at 09:44
  • btw I want the cursor to appear on the right side of the text. Plus I want to disable the onscreen keyboard. how do i do that? thanks – Seemab Hassan Feb 07 '14 at 10:02
  • You should open a new question for that as those are totally different topics. Or look here http://stackoverflow.com/questions/6217378/place-cursor-at-the-end-of-text-in-edittext – chuky Feb 07 '14 at 10:12
0

This code is when i was learning Android Application Development, and I am sharing it with you. May be you can get some idea from here, hope it helps:

Layout:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*" >

    <TableRow>

        <EditText
            android:id="@+id/editText"
            android:layout_span="4"
            android:editable="false"
            android:gravity="right"
            android:hint="Your text here..." />
    </TableRow>

    <View
        android:layout_height="2px"
        android:background="#00ff00" />

    <TableRow>

        <Button
            android:id="@+id/button1"
            android:text="1" />

        <Button
            android:id="@+id/button2"
            android:text="2" />

        <Button
            android:id="@+id/button3"
            android:text="3" />

        <Button
            android:id="@+id/buttonAdd"
            android:text="+" />
    </TableRow>

    <TableRow>

        <Button
            android:id="@+id/button4"
            android:text="4" />

        <Button
            android:id="@+id/button5"
            android:text="5" />

        <Button
            android:id="@+id/button6"
            android:text="6" />

        <Button
            android:id="@+id/buttonSub"
            android:text="-" />
    </TableRow>

    <TableRow>

        <Button
            android:id="@+id/button7"
            android:text="7" />

        <Button
            android:id="@+id/button8"
            android:text="8" />

        <Button
            android:id="@+id/button9"
            android:text="9" />

        <Button
            android:id="@+id/buttonMul"
            android:text="*" />
    </TableRow>

    <TableRow>

        <Button
            android:id="@+id/button0"
            android:layout_span="2"
            android:text="0" />

        <Button
            android:id="@+id/buttonClear"
            android:text="Clr" />

        <Button
            android:id="@+id/buttonDiv"
            android:text="/" />
    </TableRow>

    <TableRow>

        <Button
            android:id="@+id/buttonEqu"
            android:layout_span="2"
            android:text="=" />

        <Button
            android:id="@+id/buttonCan"
            android:text="C" />

        <Button
            android:id="@+id/buttonPow"
            android:text="^" />
    </TableRow>

</TableLayout>

Activity:

public class MyFirstCalculator extends Activity implements OnClickListener
{
/** Called when the activity is first created. */

Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9;
Button btnAdd,btnSub,btnMul,btnDiv,btnPow,btnEqu,btnCan,btnClr;
EditText editText;
Double oldValue;
char chOp=' ';

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    editText=(EditText) findViewById(R.id.editText);

    btn0 = (Button)findViewById(R.id.button0);
    btn1 = (Button)findViewById(R.id.button1);
    btn2 = (Button)findViewById(R.id.button2);
    btn3 = (Button)findViewById(R.id.button3);
    btn4 = (Button)findViewById(R.id.button4);
    btn5 = (Button)findViewById(R.id.button5);
    btn6 = (Button)findViewById(R.id.button6);
    btn7 = (Button)findViewById(R.id.button7);
    btn8 = (Button)findViewById(R.id.button8);
    btn9 = (Button)findViewById(R.id.button9);

    btnAdd = (Button)findViewById(R.id.buttonAdd);
    btnSub = (Button)findViewById(R.id.buttonSub);
    btnMul = (Button)findViewById(R.id.buttonMul);
    btnDiv = (Button)findViewById(R.id.buttonDiv);
    btnPow = (Button)findViewById(R.id.buttonPow);

    btnEqu = (Button)findViewById(R.id.buttonEqu);
    btnCan = (Button)findViewById(R.id.buttonCan);
    btnClr = (Button)findViewById(R.id.buttonClear);

    btn0.setOnClickListener(this);
    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);

    btnAdd.setOnClickListener(this);
    btnSub.setOnClickListener(this);
    btnDiv.setOnClickListener(this);
    btnMul.setOnClickListener(this);
    btnPow.setOnClickListener(this);
    btnEqu.setOnClickListener(this);
    btnCan.setOnClickListener(this);
    btnClr.setOnClickListener(this);
}

public void onClick(View v)
{
    try 
    {   
        Button btn = (Button)v;
        Double answer, curValue;

        switch(v.getId())
        {
            case R.id.button0:
            case R.id.button1:
            case R.id.button2:
            case R.id.button3:
            case R.id.button4:
            case R.id.button5:
            case R.id.button6:
            case R.id.button7:
            case R.id.button8:
            case R.id.button9:

                editText.setText(editText.getText()+""+btn.getText()+"");
                break;

            case R.id.buttonAdd:
            case R.id.buttonSub:
            case R.id.buttonMul:
            case R.id.buttonDiv:
            case R.id.buttonPow:

                if(editText.getText()+"" == "")
                {
                    return;
                }
                chOp=(btn.getText()+"").charAt(0);
                oldValue=Double.parseDouble(editText.getText()+"");
                editText.setText("");
                break;

            case R.id.buttonCan:

                oldValue=0.0;
                editText.setText("");
                break;

            case R.id.buttonClear:

                int len = (editText.getText()+"").length();
                if(len==0)
                {
                    Toast.makeText(getApplicationContext(), "Nothing to erase...", Toast.LENGTH_LONG).show();
                }
                else
                {
                    editText.setText((editText.getText()+"").substring(0, len-1));
                    break;
                }



            case R.id.buttonEqu:

                if(editText.getText()+"" == "")
                {
                    return;
                }
                curValue = Double.parseDouble(editText.getText()+"");
                switch (chOp)
                {
                    case '+':

                        answer = oldValue+curValue;
                        editText.setText(answer+"");
                        break;

                    case '-':

                        answer=oldValue-curValue;
                        editText.setText(answer+"");
                        break;

                    case '*':

                        answer=oldValue*curValue;
                        editText.setText(answer+"");
                        break;

                    case '/':

                        answer=oldValue/curValue;
                        editText.setText(answer+"");
                        break;

                    case '^':

                        answer=Math.pow(oldValue, curValue);
                        editText.setText(answer+"");
                        break;
                }
        }
    } 

    catch (Exception e)
    {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
    }
}
}

Note: I dont remember if the code is complete or not, or whether it runs properly or not, as it was written one year ago.

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174