简体   繁体   English

确保Integer.parseInt(String)是Java中的有效int

[英]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. 我正在使用EditText对象和getText()从用户输入的内容中检索文本。 Then I convert that to a string, and finally convert everything to an int using Integer.parseint(String) . 然后,我将其转换为字符串,最后使用Integer.parseint(String)将所有内容转换为int。 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. 我使用height.getText().length() > 0来确保用户至少在该字段中放置了一些内容,但是如果用户放置了字符,则该程序将崩溃。

The (???) is the assertion I am trying to complete here, that will return a false when the result isn't a valid int. (???)是我要在此处完成的断言,当结果不是有效的int时,它将返回false。 Also note that I initialized mHeight as a primitive int here int mHeight 还要注意,我在这里将mHeight初始化为基本int int mHeight

Note : height is an EditText object and I initialized it like so: height = (EditText) findViewById(R.id.height); 注意 :height是一个EditText对象,我将其初始化为: 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 使用height.getText().matches("\\\\d+")检查是否仅是数字

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 如果您只是想获取数字,请在您的EditText中添加inputType属性

like 喜欢

                android:inputType="numberDecimal"

then users can only enter numbers into the EditText,hence no error while parsing it. 那么用户只能在EditText中输入数字,因此解析时不会出现错误。

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

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