2012-02-04 82 views
-1

我对Java以及Android编程都很陌生。我试图制作一个计算器。但是,一旦我插入了平方根按钮,应用程序崩溃,只要我击中分裂或平方根。我不知道我要去哪里错。请帮助?Android,请告诉我我的错误

public class MainScreen extends Activity implements OnClickListener { 
     EditText edit1, edit2; 
     TextView txt; 
     Button butt, diff, mul, div, sqr, per; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 


     edit1 = (EditText)findViewById(R.id.editText1); 
     edit2 = (EditText)findViewById(R.id.editText2); 


     txt = (TextView)findViewById(R.id.textView1); 



     butt = (Button)findViewById(R.id.button1); 
     butt.setOnClickListener(this); 
     diff = (Button)findViewById(R.id.button2); 
     diff.setOnClickListener(this); 
     mul = (Button)findViewById(R.id.button3); 
     mul.setOnClickListener(this); 
     div = (Button)findViewById(R.id.button4); 
     div.setOnClickListener(this); 
     sqr = (Button)findViewById(R.id.button5); 
     sqr.setOnClickListener(this); 
     per = (Button)findViewById(R.id.button6); 
     per.setOnClickListener(this); 
     } 


    @Override 
    public void onClick(View v) { 
     String a; 
     // TODO Auto-generated method stub 
     String b; 
     Integer sum, sub, mul, div; 
     Double x ; 



     a= edit1.getText().toString(); 
     b= edit2.getText().toString(); 
     x=(double) Integer.parseInt(a); 

     switch (v.getId()) { 

      case R.id.button1: 
      sum = Integer.parseInt(a)+ Integer.parseInt(b); 
      txt.setText(sum.toString()); 
      break; 

      case R.id.button2: 
      sub = Integer.parseInt(a)- Integer.parseInt(b); 
      txt.setText(sub.toString()); 
      break; 

      case R.id.button3: 
      mul = Integer.parseInt(a)* Integer.parseInt(b); 
      txt.setText(mul.toString()); 
      break; 

      case R.id.button4: 
      div = (Integer.parseInt(a))/(Integer.parseInt(b)); 
      txt.setText(div.toString()); 

      case R.id.button5: 
      txt.setText((int) Math.sqrt(x)); 


      default: 
      break; 
     }}} 
+2

包括堆栈跟踪。 – 2012-02-04 13:52:59

回答

2
  1. 使用(int) Math.sqrt(x)不好主意 - sqrt不返回整数。

  2. 当您编写textView.setText(int) - Andrid认为,您提供字符串资源的id,并且它无法找到它并崩溃。

使用此:

case R.id.button5: 
    txt.setText(String.valueOf(Math.sqrt(x))); 
    break; 
+2

哈,好抓。 – dmon 2012-02-04 14:05:17

+0

谢谢Jin,sqrt现在正在完美工作。但分割按钮返回与sqrt相同的结果。我无法弄清楚为什么。绝对没有关系。 – Chocolava 2012-02-04 14:22:47

+0

你忘了'break'声明:) – Jin35 2012-02-04 14:24:04

1

您需要进行检查的值是确保你没有被0

分割可否请您发表您收到的错误?

+0

没有错误,它只是崩溃。 – Chocolava 2012-02-04 14:25:59

1

那么,你可以查看$ adb logcat的错误。此外,在最后两个'案例'中,你还没有放弃“休息”。

+0

我是多么愚蠢!谢谢。 – Chocolava 2012-02-04 14:31:11