Math with an integer obtained from an EditText

2019-08-29 03:16发布

问题:

I don't know what I am doing wrong but I have an edittext called input, where the user writes a number, then you press a button:

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

    XX= (Button) findViewById(R.id.XX);
    XX.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            if(XX.equals("XX"))
            {


                String aa= String.valueOf(input) ;
                float operation= ((float) ( 0.029 * 2.2 *aa ) );
                String cadena= String.valueOf(operation) ;

// set text to cadena (result of the operation)
                predic = (TextView) findViewById(R.id.predic);
                predic.setText(cadena);

            }

the problem is that I can't perform this operation

float operation= ((float) ( 0.029 * 2.2 *aa ) );

because it underlines "aa" and says

"Operator '*'cannot be applied to 'double', 'java.lang.String' "

I suppose that he thinks that aa is an String, how can I make it to be read as an Int?

LOGCAT1

09-07 23:18:07.915  10148-10148/com.example.XXXE/AndroidRuntime﹕ FATAL EXCEPTION: main
        java.lang.NumberFormatException: unable to parse 'android.widget.EditText@405a8b98' as integer
        at java.lang.Integer.parse(Integer.java:383)
        at java.lang.Integer.parseInt(Integer.java:372)
        at java.lang.Integer.parseInt(Integer.java:332)

    ***at com.example.XXX.XXX$5.onClick(XXX.java:542)***  CRASHES


    at android.view.View.performClick(View.java:2506)
    at android.view.View$PerformClick.run(View.java:9112)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3835)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
    at dalvik.system.NativeStart.main(Native Method)
09-07 23:18:07.965   3698-17447/system_process W/ActivityManager﹕ 
    Force finishing    activity com.example.XXXX/.XXXX

回答1:

You need to change:

 String aa= String.valueOf(input) ;

To

Int aa = Integer.parseInt(input.getText().toString());

As long as you are sure that the user will only be entering integers