简体   繁体   中英

Math with an integer obtained from an EditText

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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