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

标签 java android

我正在尝试获取有关用户的一些基本信息,例如高度、体重等。

我正在使用 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
  }
}

关于java - 确保 Integer.parseInt(String) 是 java 中的有效 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44547737/

相关文章:

java - 为什么javac任务不创建类

android - 移动应用程序 : Localfiles VS LocalDB?

Android 共享元素返回过渡到上一个 Activity

java - 如何在不创建对象的情况下将java类转换为json格式结构

java - 改进 Java API 文档?

java - Android Java 无法在 XML 文件按钮中找到可绘制对象

java - 向右移动 wicket paginnavigator

android - 在新 Activity 中获取 Intent 的 Extra 内容

android - 检查 (ParseUser.getCurrentUser() != null) 时出现 NullPointerException

android - 如何在 Android 上的 Chrome 上调试 "add to home screen"?