简体   繁体   English

android应用上的if语句帮助

[英]if statement help on android app

iv created an android app, what my problem is that when i press the + = - / * buttons before i input a number my app stops working, is there anyway i can make it that if there is no number input it doesnt stop working? iv创建了一个android应用程序,我的问题是,当我在输入数字之前按+ =-/ *按钮我的应用程序停止工作时,无论如何我都能做到,如果没有数字输入就不会停止工作?


package steven.mcilhone.calculatorcoursework;

import java.math.BigDecimal;


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


public class Calculator extends Activity {

EditText firstValue;
EditText secondValue;
TextView result;
Button addbtn, subtractbtn, dividebtn, multiplybtn, equalbtn, clearbtn;
BigDecimal firstNum, secondNum;



String Operator = "";

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

    addbtn = (Button) findViewById(R.id.addbtnID);
    subtractbtn = (Button) findViewById(R.id.subtractbtnID);
    dividebtn = (Button) findViewById(R.id.dividebtnID);
    multiplybtn = (Button) findViewById(R.id.multiplybtnID);
    equalbtn = (Button) findViewById(R.id.equalbtnID);
    clearbtn = (Button) findViewById(R.id.clearbtn);
    firstValue = (EditText) findViewById(R.id.edttxt1);
    secondValue = (EditText) findViewById(R.id.edttxt1);


    clearbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText edttxt1 = (EditText) findViewById(R.id.edttxt1);
            edttxt1.setText("");
        }
    });



    addbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            Operator = "+";
            addandclear();
        }
    });

    subtractbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Operator = "-";             
            addandclear();
        }
    });

    dividebtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Operator = "/";
            addandclear();

        }
    });

    multiplybtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Operator = "*";
            addandclear();
        }
    });

    equalbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            secondNum = new          BigDecimal(secondValue.getText().toString());
            EditText edttxt1 = (EditText) findViewById(R.id.edttxt1);
            edttxt1.setText("");
            if (Operator == "+"){
                edttxt1.setText(firstNum.add(secondNum).toString());
            }
            else if (Operator == "-"){
                edttxt1.setText(firstNum.subtract(secondNum).toString());
            }
            else if (Operator == "/"){
                edttxt1.setText(firstNum.divide(secondNum).toString());
            }   
            else if (Operator == "*"){
                edttxt1.setText(firstNum.multiply(secondNum).toString());
            }   



        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_calculator, menu);
    return true;
}


        public void addandclear(){


            firstNum = new BigDecimal(firstValue.getText().toString());             
            EditText edttxt1 = (EditText) findViewById(R.id.edttxt1);
            edttxt1.setText("");
        }



}

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<EditText
    android:id="@+id/edttxt1"
    android:layout_width="250dp"
    android:layout_height="100dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="?android:attr/editTextBackground"
    android:ems="15"
    android:inputType="numberDecimal" 
    android:gravity="right"/>

<Button
    android:id="@+id/addbtnID"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_below="@+id/edttxt1"
    android:layout_marginLeft="20dp"
    android:text="@string/add" />

<Button
    android:id="@+id/dividebtnID"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_below="@+id/edttxt1"
    android:layout_toRightOf="@+id/addbtnID"
    android:text="@string/divide" />

<Button
    android:id="@+id/multiplybtnID"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_below="@+id/edttxt1"
    android:layout_toRightOf="@+id/dividebtnID"
    android:text="@string/multiply" />

<Button
    android:id="@+id/subtractbtnID"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_alignBaseline="@+id/multiplybtnID"
    android:layout_alignBottom="@+id/multiplybtnID"
    android:layout_toRightOf="@+id/multiplybtnID"
    android:text="@string/subtract" />

<Button
    android:id="@+id/zerobtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_alignLeft="@+id/addbtnID"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/twobtn"
    android:text="@string/zero" />

<Button
    android:id="@+id/onebtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/zerobtn"
    android:layout_alignLeft="@+id/zerobtn"
    android:text="@string/one" />

<Button
    android:id="@+id/twobtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/zerobtn"
    android:layout_toLeftOf="@+id/multiplybtnID"
    android:text="@string/two" />

<Button
    android:id="@+id/threebtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/zerobtn"
    android:layout_toLeftOf="@+id/subtractbtnID"
    android:text="@string/three" />

<Button
    android:id="@+id/fourbtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/onebtn"
    android:layout_toLeftOf="@+id/twobtn"
    android:text="@string/four" />

<Button
    android:id="@+id/fivebtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_alignBaseline="@+id/fourbtn"
    android:layout_alignBottom="@+id/fourbtn"
    android:layout_toLeftOf="@+id/threebtn"
    android:text="@string/five" />

<Button
    android:id="@+id/sixbtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_alignBaseline="@+id/fivebtn"
    android:layout_alignBottom="@+id/fivebtn"
    android:layout_toRightOf="@+id/fivebtn"
    android:text="@string/six" />

<Button
    android:id="@+id/sevenbtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/fourbtn"
    android:layout_toLeftOf="@+id/fivebtn"
    android:text="@string/seven" />

<Button
    android:id="@+id/eightbtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/fivebtn"
    android:layout_toLeftOf="@+id/sixbtn"
    android:text="@string/eight" />

<Button
    android:id="@+id/ninebtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_alignBaseline="@+id/eightbtn"
    android:layout_alignBottom="@+id/eightbtn"
    android:layout_toRightOf="@+id/eightbtn"
    android:text="@string/nine" />

<Button
    android:id="@+id/equalbtnID"
    android:layout_width="70dp"
    android:layout_height="120dp"
    android:layout_alignBottom="@+id/threebtn"
    android:layout_alignTop="@+id/sixbtn"
    android:layout_toRightOf="@+id/threebtn"
    android:text="@string/equal" />

<Button
    android:id="@+id/clearbtn"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_above="@+id/equalbtnID"
    android:layout_alignLeft="@+id/equalbtnID"
    android:text="@string/clear" />

</RelativeLayout>
 if (Operator == "+"){

should be 应该

 if (Operator.eqauls("+")){

Same applies for other if/else blocks in your code. 同样适用于代码中的其他if / else块。

It is always better to us .equals() instead of == while comparing Strings (except the case of String literals, String literals may pass == condition). 在比较字符串时,对我们来说总是最好用.equals()而不是== (字符串类型除外,字符串常量可以通过==条件)。

== checks for reference equality. ==检查引用是否相等。 equals() checks for content equality. equals()检查内容是否相等。 This discussion may help you. 此讨论可能会对您有所帮助。

EDIT: 编辑:

As TedHopp commented, your code referring to compile time constants, String comparison may not be issue here, still above answers stands as good practice for String comparison. 正如TedHopp所评论的那样,您的代码可能不涉及编译时间常数,即字符串比较,这里的答案仍然是字符串比较的好习惯。

Because there is no stacktrace available with question, assuming flow satisfies one of the if/else conditions, one other possibility for error is NumberFormatException . 因为没有问题可用的堆栈跟踪,所以假设流满足if / else条件之一,则发生错误的另一种可能性是NumberFormatException

Maek sure the numbers you are reading from EditText are valid Number before creating BigDecimal(String) instance. 在创建BigDecimal(String)实例之前,请确保从EditText读取的数字是有效Number。

In several places, you are converting the user input to a BigDecimal without doing any error checking. 在许多地方,您将用户输入转换为BigDecimal而不进行任何错误检查。 In particular, when there is no input, new BigDecimal(String) will generate a NumberFormatException because "" is not a valid number. 特别是,当没有输入时, new BigDecimal(String)将生成NumberFormatException因为“”不是有效数字。 From the docs : 文档

The string must contain at least one digit in either the integer or the fraction. 该字符串必须包含至少一位整数或小数位。

Find every place where you are using the user input and put in some error checking. 查找使用用户输入的每个位置,然后进行一些错误检查。 For instance, in addandclear() : 例如,在addandclear()

public void addandclear(){
    String val = firstValue.getText().toString();
    try {
        firstNum = new BigDecimal(val);
        EditText edttxt1 = (EditText) findViewById(R.id.edttxt1);
        edttxt1.setText("");
    } catch (NumberFormatException e) {
        if (val.length() == 0) {
            // blank field
        } else {
            // something wrong with the input
        }
    }
}

To reduce code you could add android:onClick="addandclear" to the buttons in the xml (make addandclear take View v as argument). 为了减少代码,您可以将android:onClick =“ addandclear”添加到xml中的按钮(使addandclear以View v作为参数)。 Then get the operator by v.getText().toString() 然后通过v.getText()。toString()获取运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM