简体   繁体   中英

Making sure Integer.parseInt(String) is a valid int in java

I am attempting to get some basic info about a user, such as height, weight, ect.

I am using EditText objects and getText() to retrieve the text from what the user has typed. Then I convert that to a string, and finally convert everything to an int using Integer.parseint(String) . Below is an example of what I am attempting to do if that was confusing.

if((height.getText().length() > 0) && (???)) {
    mHeight = Integer.parseInt(height.getText().toString());
} else {
    Toast.makeText(getBaseContext(), "Please enter your height, in inches, rounded to the nearest inch", Toast.LENGTH_SHORT).show();
    canContinue = -1;
}

I used height.getText().length() > 0 to make sure that the user has at least put something into the field, but if the user puts characters, then the program crashes.

The (???) is the assertion I am trying to complete here, that will return a false when the result isn't a valid int. Also note that I initialized mHeight as a primitive int here int mHeight

Note : height is an EditText object and I initialized it like so: height = (EditText) findViewById(R.id.height);

Short of doing some complicated validations, I would simply try to parse and catch any exceptions.

//test that the value is not empty and only contains numbers
//to deal with most common errors
if(!height.getText().isEmpty() && height.getText().matches("\\d+")) {
  try {
    mHeight = Integer.parseInt(height.getText());
  } catch (NumberFormatException e) { //will be thrown if number is too large
    //error handling
  }
}

use height.getText().matches("\\\\d+") to check if that is a number only

like:

if((height.getText().length() > 0) && height.getText().toString().matches("\\d+")) {

}

Write the following method and call it instead of "???"

    public static boolean isNumeric(String str)  
    {  
      try  
      {  
        int d = Integer.parseInt(str);  
      }  
      catch(NumberFormatException nfe)  
      {  
        return false;  
      }  
      return true;  
    }

Just try parsing it an catch any exceptions:-

try {
    int mHeight = 0;
    if (height.getText().length() > 0) {
        mHeight = Integer.parseInt(height.getText().toString());
    }
} catch (NumberFormatException ex) {
    Toast.makeText(getBaseContext(), "Please enter your height, in inches, rounded to the nearest inch", Toast.LENGTH_SHORT).show();
    canContinue = -1;
}   

If you are just trying to get numbers add inputType attribute to your EditText

like

                android:inputType="numberDecimal"

then users can only enter numbers into the EditText,hence no error while parsing it.

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