簡體   English   中英

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

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

我正在嘗試獲取有關用戶的一些基本信息,例如身高,體重等。

我正在使用EditText對象和getText()從用戶輸入的內容中檢索文本。 然后,我將其轉換為字符串,最后使用Integer.parseint(String)將所有內容轉換為int。 下面是一個我試圖做的令人困惑的示例。

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;
}

我使用height.getText().length() > 0來確保用戶至少在該字段中放置了一些內容,但是如果用戶放置了字符,則該程序將崩潰。

(???)是我要在此處完成的斷言,當結果不是有效的int時,它將返回false。 還要注意,我在這里將mHeight初始化為基本int int mHeight

注意 :height是一個EditText對象,我將其初始化為: height = (EditText) findViewById(R.id.height);

除了進行一些復雜的驗證之外,我只是嘗試解析並捕獲任何異常。

//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
  }
}

使用height.getText().matches("\\\\d+")檢查是否僅是數字

喜歡:

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

}

編寫以下方法,然后調用它而不是“ ???”

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

只需嘗試解析它即可捕獲任何異常:

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;
}   

如果您只是想獲取數字,請在您的EditText中添加inputType屬性

喜歡

                android:inputType="numberDecimal"

那么用戶只能在EditText中輸入數字,因此解析時不會出現錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM