Converting EditText to int? (Android)

前端 未结 11 1238
深忆病人
深忆病人 2020-12-09 03:08

I am wondering how to convert an edittext input to an int, I have the user input a number, it than divides it by 8.

MainActivity.java

@SuppressWarnin         


        
11条回答
  •  忘掉有多难
    2020-12-09 03:41

    You can use parseInt with try and catch block

    try
    {
        int myVal= Integer.parseInt(mTextView.getText().toString());
    }
    catch (NumberFormatException e)
    {
        // handle the exception
        int myVal=0;
    }
    

    Or you can create your own tryParse method :

    public Integer tryParse(Object obj) {
        Integer retVal;
        try {
            retVal = Integer.parseInt((String) obj);
        } catch (NumberFormatException nfe) {
            retVal = 0; // or null if that is your preference
        }
        return retVal;
    }
    

    and use it in your code like:

    int myVal= tryParse(mTextView.getText().toString());
    

    Note: The following code without try/catch will throw an exception

    int myVal= new Integer(mTextView.getText().toString()).intValue();
    

    Or

    int myVal= Integer.decode(mTextView.getText().toString()).intValue();
    

提交回复
热议问题